创建方法来更新&保存文件与猫鼬? [英] Creating methods to update & save documents with mongoose?
问题描述
在查看官方文档后,我仍然不确定如何创建在 mongoose
创建&更新文件。
那么我该怎么做?
我有这样的想法: p>
mySchema.statics.insertSomething = function insertSomething(){
return this.insert(()?
}
方法用于与当前实例示例:
var AnimalSchema = new Schema({
name:String
,type: String
});
//我们要在Animal
的实例上使用此属性AnimalSchema.methods.findSimilarType = function findSimilarType(cb){
返回此.find({type:this.type},cb);
};
var Animal = mongoose.model('Animal',AnimalSchema);
var dog = new Animal({name:'Rover',type:'dog'});
// dog是Animal的一个实例
dog.findSimilarType(function(err,dogs)){
if(err)return ...
dogs.forEach(..);
})
当您不想与实例进行交互时,会使用静态,但可以进行与模型相关的内容(例如,搜索所有名为Rover的动物)。 p>
如果要插入/更新模型的实例(在数据库中),则方法
是走。如果您只需要保存/更新内容,可以使用 save
函数(已经存在于Mongoose中)。示例:
var Animal = mongoose.model('Animal',AnimalSchema);
var dog = new Animal({name:'Rover',type:'dog'});
dog.save(function(err){
//我们已将狗保存到db中
if(err)throw err;
dog。 name =Spike;
dog.save(function(err){
//我们已将狗更新到db中
if(err)throw err;
});
});
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(() ?
}
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;
});
});
这篇关于创建方法来更新&保存文件与猫鼬?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!