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?
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.
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