创build方法来更新和保存与mongoose的文件?

查看官方文档后 ,我仍然不确定如何创buildmongoose内部使用的方法来创build和更新文档。

那我该怎么做呢?

我有这样的想法:

 mySchema.statics.insertSomething = function insertSomething () { return this.insert(() ? } 

方法用于与模型的当前实例进行交互。 例:

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

当你不想与一个实例进行交互时使用静态,但是做与模型有关的东西(例如search名为“Rover”的所有动物)。

如果你想插入/更新模型的实例(到数据库),那么methods是要走的路。 如果你只需要保存/更新的东西,你可以使用savefunction(已经存在到Mongoose中)。 例:

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

从静态方法中,您也可以通过执行以下操作来创build新文档:

 schema.statics.createUser = function(callback) { var user = new this(); user.phone_number = "jgkdlajgkldas"; user.save(callback); }; 

不要以为你需要创build一个调用.save()的函数。 保存模型之前需要做的任何事情都可以使用.pre()

如果您想检查模型是否正在创build或更新,请检查this.isNew()