Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose create a new object within a static function

How do I create a new object within one of my static methods defined in the schema?

I basically have

UserSchema.statics.createUser = function (username, password, cb) { .. }

And I want to be able to save a new instance of the user object inside the function. I want to do something like var user = new User(...) within that method, but it of course doesn't work because the User model was not yet created.

What do I do?

like image 583
Andrei Ivanov Avatar asked Oct 13 '15 01:10

Andrei Ivanov


1 Answers

When you first call the static function this is bound to the model for the schema. You can just do something like this:

someSchema.static('foo', function() {
    const newUser = new this({
        username: username, 
        password: password,
    });
    newUser.save(cb);
})

Don't replace the anonymous function with a fat arrow equivalent (I know you want to!). this won't have the correct scope.

like image 57
Robert Moskal Avatar answered Sep 28 '22 08:09

Robert Moskal