Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - add method to object that is returned in the callback

Is there a way to add functions to the object that is returned in the callback?

User.find({'age':'20'}, function(err, users){
    users.function();
});

It seems statics only work on the model. Schematically :

User.static();

and methods only work on instances

(new User()).method();

None of them seem to work on users, which i think is just a normal js Object variable. Am I missing something ?

like image 675
Radioreve Avatar asked Oct 26 '25 18:10

Radioreve


1 Answers

The Schema.method description, from the docs:

Adds an instance method to documents constructed from Models compiled from this schema.

So, if you do something like this:

var userSchema = new Schema({
    username: String,
    age: Number
});

userSchema.method('showAge', function () {
    return this.age;
});

, and call your method in a document returned from a query like:

User.findOne({'age':'20'}, function(err, user){
    console.log(user.showAge());
});

it should work. Maybe you're having problems because you're calling your method users.function() in an array. Remember: the find method returns an array of documents.

like image 148
Rodrigo Medeiros Avatar answered Oct 29 '25 07:10

Rodrigo Medeiros



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!