Mongoose create multiple documents

后端 未结 4 893
粉色の甜心
粉色の甜心 2020-12-29 19:39

I know in the latest version of Mongoose you can pass multiple documents to the create method, or even better in my case an array of documents.

var array = [         


        
相关标签:
4条回答
  • 2020-12-29 20:08

    You can access the variable list of parameters to your callback via arguments. So you could do something like:

    Candy.create(array, function (err) {
        if (err) // ...
    
        for (var i=1; i<arguments.length; ++i) {
            var candy = arguments[i];
            // do some stuff with candy
        }
    });
    
    0 讨论(0)
  • 2020-12-29 20:12

    by insert function of collection db, example:

    Model.collection.insert(array, (err, list) => {
      if (err) throw err;
    
      console.log('list:', list);
    });
    
    0 讨论(0)
  • 2020-12-29 20:18

    With Mongoose v5.1.5, we can use insertMany() method with array passed.

    const array = [
        {firstName: "Jelly", lastName: "Bean"},
        {firstName: "John", lastName: "Doe"}
    ];
    
    Model.insertMany(array)
        .then(function (docs) {
            response.json(docs);
        })
        .catch(function (err) {
            response.status(500).send(err);
        });
    
    0 讨论(0)
  • 2020-12-29 20:29

    According to this ticket on GitHub, Mongoose 3.9 and 4.0 will return an array if you supply an array and a spread of arguments if you supply a spread when using create().

    0 讨论(0)
提交回复
热议问题