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.
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);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With