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

后端 未结 4 1679
走了就别回头了
走了就别回头了 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)
    

    });

提交回复
热议问题