【问题标题】:Nodejs/mongoose. which approach is preferable to create a document?Nodejs/猫鼬。哪种方法更适合创建文档?
【发布时间】:2012-03-07 12:55:42
【问题描述】:

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

第一

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

第二

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

有什么不同吗?

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,很好的解释:)
    • 除此之外,您需要自己生成 id。 mongoose.Types.ObjectId() 是 _id 的格式。
    • 异步和同步怎么样,都是同步的吗?
    • 这没有多大意义。使用 Model.create 仍然可以解决您提出的所有情况。如果您一开始就没有创建文档(而不是模型),为什么还要放弃它?
    【解决方案2】:

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

       // Create new user.
       let newUser = {
           username: req.body.username,
           password: passwordHashed,
           salt: salt,
           authorisationKey: authCode
       };
    
       // From require('UserModel');
       return ModelUser.create(newUser);
    

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

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

    【讨论】:

      【解决方案3】:

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

      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)' 允许创建一个名称为模型的集合并执行.save() 方法,仅将文档写入数组。

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

      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)
      

      });

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2016-10-06
          • 2012-02-17
          • 2015-09-06
          • 2012-11-05
          • 1970-01-01
          • 1970-01-01
          • 2016-12-17
          • 2018-11-09
          • 1970-01-01
          相关资源
          最近更新 更多