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

后端 未结 4 1675
走了就别回头了
走了就别回头了 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:34

    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.

    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)
    

    });

    0 讨论(0)
  • 2020-12-13 04:41

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

    0 讨论(0)
  • 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) {
      //
    });
    
    0 讨论(0)
  • 2020-12-13 04:47

    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.
    });
    
    0 讨论(0)
提交回复
热议问题