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 AnimalAnimalSchema.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 Animaldog.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; });});