Nodejs/猫鼬。哪种方法更适合创建文档?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9305987/
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:11:54  来源:igfitidea点击:

Nodejs/mongoose. which approach is preferable to create a document?

node.jsmongoose

提问by Erik

I've found two approach to create new document in nodejs when I work with mongoose.

当我使用 mongoose 时,我发现了两种在 nodejs 中创建新文档的方法。

First:

第一

var instance = new MyModel();
instance.key = 'hello';
instance.save(function (err) {
  //
});

Second

第二

MyModel.create({key: 'hello'}, function (err) {
  //
});

Is there any difference?

有什么区别吗?

回答by Swift

Yes, the main difference is the ability to do computations before you save or as a reaction to information that comes up while you're building your new model. The most common example would be making sure the model is valid before trying to save it. Some other examples might be creating any missing relations before saving, values that need to be calculated on the fly based on other attributes, and models that need to exist but could potentially never be saved to the database (aborted transactions).

是的,主要区别在于能够在保存之前进行计算,或者作为对构建新模型时出现的信息的反应。最常见的例子是在尝试保存模型之前确保模型有效。其他一些示例可能是在保存之前创建任何缺失的关系、需要根据其他属性动态计算的值以及需要存在但可能永远不会保存到数据库中的模型(中止的事务)。

So as a basic example of some of the things you could do:

因此,作为您可以做的一些事情的基本示例:

var instance = new MyModel();

// Validating
assert(!instance.errors.length);

// Attributes dependent on other fields
instance.foo = (instance.bar) ? 'bar' : 'foo';

// Create missing associations
AuthorModel.find({ name: 'Johnny McAwesome' }, function (err, docs) {
  if (!docs.length) {
     // ... Create the missing object
  }
});

// Ditch the model on abort without hitting the database.
if(abort) {
  delete instance;
}

instance.save(function (err) {
  //
});

回答by Morris

This code is for saving an array of documents into Database:

此代码用于将文档数组保存到数据库中:

app.get("/api/setupTodos", function (req, res) {

var nameModel = mongoose.model("nameModel", yourSchema);
//create an array of documents
var listDocuments= [
    {
        username: "test",
        todo: "Buy milk",
        isDone: true,
        hasAttachment: false
    },
    {
        username: "test",
        todo: "Feed dog",
        isDone: false,
        hasAttachment: false
    },
    {
        username: "test",
        todo: "Learn Node",
        isDone: false,
        hasAttachment: false
    }
];

nameModel.create(listDocuments, function (err, results) {

    res.send(results);
});

'nameModel.create(listDocuments)' permit that create a collection with name of model and execute .save()method for only document into array.

'nameModel.create(listDocuments)' 允许创建一个带有模型名称的集合,并.save()只为文档到数组中执行方法。

Alternatively, you can save one only document in this way:

或者,您可以通过以下方式仅保存一个文档:

var myModule= mongoose.model("nameModel", yourSchema);

    var firstDocument = myModule({
      name: String,
surname: String
    });

firstDocument.save(function(err, result) {
  if(if err) throw err;
  res.send(result)

});

});

回答by Oliver Dixon

I prefer an easy example with pre-defined user values and validation checking model side.

我更喜欢带有预定义用户值和验证检查模型方面的简单示例。

   // Create new user.
   let newUser = {
       username: req.body.username,
       password: passwordHashed,
       salt: salt,
       authorisationKey: authCode
   };

   // From require('UserModel');
   return ModelUser.create(newUser);

Then you should be using validators in the model class (Because this can be used in other locations, this will help reduce errors/speed up development)

那么你应该在模型类中使用验证器(因为这可以在其他位置使用,这将有助于减少错误/加速开发)

// Save user but perform checks first.
gameScheme.post('pre', function(userObj, next) {
    // Do some validation.
});

回答by iAviator

Create will create a new document while save is used for updating the document.

Create 将创建一个新文档,而 save 用于更新文档。