user1772306 user1772306 - 4 months ago 46
Node.js Question

Mongoose/NodeJS defining static/method for saving a document

I'd like to define my own static/method do save a document of my model.

I've tried this:

userSchema.statics.saveUser = function(data, callback){
data.save(callback);
};


It says data.save() is not a function. It doesn't recognize the function.

Then i tried this

userSchema.statics.saveUser = function(data, callback){
data = new userSchema(data);
data.save(callback);
};


userSchema is not a function.

Answer

Methods and statics are not the same. The former are found on documents (model instances) while the latter on the model. If the above is intended to be used as a static, creating a user or something, you would:

userModel.saveUser();

However I don't really see what good that would do as you're not passing it any data. If you instead create it as a method it would look like this:

userSchema.methods.saveUser = function(callback){
    user.save(callback);
};

And you would call it like:

var doc = new userModel();
// Set stuff
doc.saveUser();

Without knowing what you actually want to do it's hard to say which way is preferable in your case.