Ind*_*ial 29 methods mongoose mongodb node.js express
在查看官方文档后,我仍然不确定如何创建用于mongoose创建和更新文档的方法.
那我该怎么做呢?
我有这样的想法:
mySchema.statics.insertSomething = function insertSomething () {
return this.insert(() ?
}
Run Code Online (Sandbox Code Playgroud)
小智 58
从静态方法内部,您还可以通过执行以下操作来创建新文档:
schema.statics.createUser = function(callback) {
var user = new this();
user.phone_number = "jgkdlajgkldas";
user.save(callback);
};
Run Code Online (Sandbox Code Playgroud)
ale*_*lex 49
方法用于与模型的当前实例交互.例:
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(..);
})
Run Code Online (Sandbox Code Playgroud)
当您不想与实例交互时,会使用静态,但会执行与模型相关的内容(例如,搜索名为"Rover"的所有动物).
如果要插入/更新模型的实例(进入数据库),那么methods就是要走的路.如果你只需要保存/更新东西,你可以使用该save功能(已经存在于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;
});
});
Run Code Online (Sandbox Code Playgroud)