Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js — mongoose static method example

I wish to define a method on a model UserModel such that I get the names of all the users that have userId < 10.

Following is my implementation:

// pseudo code
UserModel === {
    userId : Number,
    userName: String
}

UserSchema.statics.getUsersWithIdLessThan10 = function(){
    var usersLessThan10 = []
    this.find({userId : {$lt : 10}}, function(error, users){
        users.forEach(function(user){
            console.log(user.userName) // ... works fine
            usersLessThan10.push(user.userName)
        })
    })
    return usersLessThan10
}

I understand why this doesn't seem to work — async find API. But if that's the case, then whats the way to do it? This async stuff is kind of overwhelming.

like image 346
p0lAris Avatar asked Mar 23 '26 21:03

p0lAris


1 Answers

Add callback and return the users in this callback as follows:

UserSchema.statics.getUsersWithIdLessThan10 = function(err, callback) {
    var usersLessThan10 = []
    this.find({userId : {$lt : 10}}, function(error, users){
        users.forEach(function(user){
            console.log(user.userName) // ... works fine
            usersLessThan10.push(user.userName)
        })
        callback(error, usersLessThan10)
    })
}

Then call usersLessThan10 with the callback:

... .usersLessThan10(function (err, users) {
    if (err) {
        // handle error
        return;
    }
    console.log(users);
})
like image 194
Alex Netkachov Avatar answered Mar 25 '26 19:03

Alex Netkachov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!