node.js 使用猫鼬创建更新和保存文档的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8987851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:03:42  来源:igfitidea点击:

Creating methods to update & save documents with mongoose?

node.jsmongodbmethodsexpressmongoose

提问by Industrial

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

查看官方文档后,我仍然不确定如何创建用于mongoose创建和更新文档的方法。

So how can I do this?

那么我该怎么做呢?

I have something like this in mind:

我有这样的想法:

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

回答by hydrozen

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

回答by alessioalex

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').

当您不想与实例交互,但要执行与模型相关的操作(例如搜索所有名为“Rover”的动物)时,将使用静态。

If you want to insert / update an instance of a model (into the db), then methodsare the way to go. If you just need to save/update stuff you can use the savefunction (already existent into Mongoose). Example:

如果你想插入/更新一个模型的实例(到数据库中),那么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;
  });
});

回答by Xerri

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

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

If you want the check if the model is being created or updated do a check for this.isNew()

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