Mongoose Query Helper

Để thêm query vào mongoose model chúng ta phải thông qua objet Schema#query.

//File query.helper.js
import mongoose from 'mongoose';

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

const UserSchema = mongoose.Schema({
    name: String
});

UserSchema.query.byName = function (name) {
    return this.where({ name: new RegExp(name, 'i') });
};

Thực nghiệm

//File query.helper.js
// more code

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

const insertUser = async (name) => {
    await new UserModel({name}).save();
}

const queryHelper = async () => {
    await insertUser("hga");
    await insertUser("hgi");
    await insertUser("rds");

    UserModel.find().byName('h').exec(function (err, users) {
        console.log("find:", users);
    });
    
    UserModel.findOne().byName('rds').exec(function (err, user) {
        console.log("findOne:", user);
    });
}

queryHelper();

Run

  • MacOS: ./node_modules/.bin/babel-node ./query.helper.js
  • Windows: .\node_modules\.bin\babel-node .\query.helper.js

Output

find: [ { _id: 5dd147e9a0e0a915e8746659, name: ‘hga’, __v: 0 },
{ _id: 5dd147e9a0e0a915e874665a, name: ‘hgi’, __v: 0 } ]
findOne: { _id: 5dd147e9a0e0a915e874665b, name: ‘rds’, __v: 0 }

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