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

后端 未结 4 1676
走了就别回头了
走了就别回头了 2020-12-13 04:06

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

First:

var instance = new MyModel();
instan         


        
4条回答
  •  無奈伤痛
    2020-12-13 04:44

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

提交回复
热议问题