Instance method trong mongoose

Instance của models là các document. Bản thân document đã có rất nhiều instance method được mongoose xây dựng sẵn. Chúng ta cũng có thể xây dựng thêm các instance method nữa thông qua Schema#methods.

// File instance.method.js

import mongoose from 'mongoose';

// connect to MongoDB
mongoose.connect('mongodb://localhost/gettingstarted', { useNewUrlParser: true });

const UserSchema = mongoose.Schema({
    email: String,
    password: String,
    fullname: String,
    gender: {
        type: String,
        enum: ['male', 'female', 'other']
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
    note: String
});


UserSchema.methods.findUserSimilarGender = function (callback) {
    return this.model('User').find({gender: this.gender}, callback);
}

Ở ví dụ trên mình xây dựng một instance method findUserSimilarGender() tìm tất cả các user có cùng giới tính với user hiện tại.

Note:

This – Tương ứng với instance của document

model(name): instance method của document được xây dựng sẵn. Trả về instance của model ứng với name truyền vào.

/**
     * Returns another Model instance.
     * @param name model name
     */
    model<T extends Document>(name: string): Model<T>;

Không được sử dụng arrow function es6 (=>) trong instance method.

// Error Cannot read property 'model' of undefined ...
UserSchema.methods.findUserSimilarGender = (callback) => {
    return this.model('User').find({gender: this.gender}, callback);
}

Kiểm tra

// File intance.method.js

// more code

const UserModel = mongoose.model('User', UserSchema);

const insertUser = async (email, password, fullname, gender) => {
    const newUser = new UserModel({
        email, password, fullname, gender
    });
    return await newUser.save();
}


const instanceMethod = async () => {
    try {
        let user = await insertUser("email1", "123", "name 1", "male");
        await insertUser("email2", "123", "name 2", "male");
        await insertUser("email3", "123", "name 3", "female");

        console.log(await user.findUserSimilarGender());
    } catch(err) {
        console.log(err);
    }
}

instanceMethod();

Run

  • MacOS: ./node_modules/.bin/babel-node ./instance.method.js
  • Windows: .\node_modules\.bin\babel-node .\instance.method.js

Output

[ { _id: 5dd1128005670b835e063762,
email: ’email1′,
password: ‘123’,
fullname: ‘name 1’,
gender: ‘male’,
createdAt: 2019-11-17T09:27:28.950Z,
__v: 0 },
{ _id: 5dd1128005670b835e063763,
email: ’email2′,
password: ‘123’,
fullname: ‘name 2’,
gender: ‘male’,
createdAt: 2019-11-17T09:27:28.991Z,
__v: 0 } ]

Kết

Cá nhân mình trong quá trình làm dự án ít khi dùng đến instance method. Mà dùng nhiều statics method hơn như là generate token, update status cho UserModel etc.

Các bạn có thể download sourcecode đầy đủ để kiểm tra kết quả.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x