Creating methods to update & save documents with mongoose?
Methods are used to to interact with the current instance of the model. Example:
var AnimalSchema = new Schema({
name: String
, type: String
});
// we want to use this on an instance of Animal
AnimalSchema.methods.findSimilarType = function findSimilarType (cb) {
return this.find({ type: this.type }, cb);
};
var Animal = mongoose.model('Animal', AnimalSchema);
var dog = new Animal({ name: 'Rover', type: 'dog' });
// dog is an instance of Animal
dog.findSimilarType(function (err, dogs) {
if (err) return ...
dogs.forEach(..);
})
Statics are used when you don't want to interact with an instance, but do model-related stuff (for example search for all Animals named 'Rover').
If you want to insert / update an instance of a model (into the db), then methods
are the way to go. If you just need to save/update stuff you can use the save
function (already existent into Mongoose). Example:
var Animal = mongoose.model('Animal', AnimalSchema);
var dog = new Animal({ name: 'Rover', type: 'dog' });
dog.save(function(err) {
// we've saved the dog into the db here
if (err) throw err;
dog.name = "Spike";
dog.save(function(err) {
// we've updated the dog into the db here
if (err) throw err;
});
});
From inside a static method, you can also create a new document by doing :
schema.statics.createUser = function(callback) {
var user = new this();
user.phone_number = "jgkdlajgkldas";
user.save(callback);
};
Don't think you need to create a function that calls .save(). Anything that you need to do before the model is saved can be done using .pre()
If you want the check if the model is being created or updated do a check for this.isNew()