Creating methods to update & save documents with mongoose?

回眸只為那壹抹淺笑 提交于 2019-12-20 08:38:24

问题


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:


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



回答2:


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



回答3:


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()



来源:https://stackoverflow.com/questions/8987851/creating-methods-to-update-save-documents-with-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!