Creating methods to update & save documents with mongoose?


Question

After checking out the official documentation, I am still not sure on how to create methods for use within mongoose to create & update documents.

So how can I do this?

I have something like this in mind:

mySchema.statics.insertSomething = function insertSomething () {
    return this.insert(() ?
}
1
29
1/24/2012 1:45:25 PM

Accepted Answer

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;
  });
});
49
1/24/2012 2:23:19 PM

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);
};

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon