如何在Mongoose / Node.js中同时保存多个文档?

时间:2012-04-22 08:45:36

标签: node.js mongodb mongoose

目前我使用save来添加单个文档。假设我有一个文档数组,我希望将其存储为单个对象。有没有办法通过单个函数调用添加它们,然后在完成后获得单个回调?我可以单独添加所有文档,但是管理回调以便在完成所有工作时都会出现问题。

13 个答案:

答案 0 :(得分:86)

Mongoose现在支持将多个文档结构传递给Model.create。引用他们的API示例,它支持传递数组或varargs对象列表,最后带有回调:

Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) {
    if (err) // ...
});

或者

var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
Candy.create(array, function (err, jellybean, snickers) {
    if (err) // ...
});

编辑:正如许多人所说,这不会执行真正的批量插入 - 它只是隐藏了自己多次调用save的复杂性。下面有答案和评论解释如何使用实际的Mongo驱动程序来实现批量插入以保证性能。

答案 1 :(得分:40)

Mongoose 4.4添加了一个名为insertMany

的方法
  

验证文档数组并将其插入的快捷方式   MongoDB,如果它们全部有效。这个函数比.create()快   因为它只向服务器发送一个操作,而不是每个操作一个   文档。

从问题#723引用vkarpov15:

  

权衡是insertMany()没有触发预保存挂钩,但它应该有更好的性能,因为它只对数据库进行1次往返,而不是每个文档1次。

该方法的签名与Model.insertMany([ ... ], (err, docs) => { ... }) 相同:

Model.insertMany([ ... ]).then((docs) => {
  ...
}).catch((err) => {
  ...
})

或者,承诺:

can't read "argv0": no such variable

答案 2 :(得分:35)

Mongoose尚未实施批量插入(请参阅issue #723)。

由于您知道要保存的文档数量,因此可以编写如下内容:

var total = docArray.length
  , result = []
;

function saveAll(){
  var doc = docArray.pop();

  doc.save(function(err, saved){
    if (err) throw err;//handle error

    result.push(saved[0]);

    if (--total) saveAll();
    else // all saved here
  })
}

saveAll();

当然,这是一个临时解决方案,我建议使用某种流量控制库(我使用q并且它很棒)。

答案 3 :(得分:25)

Mongoose中的批量插入可以使用.insert()完成,除非您需要访问中间件。

Model.collection.insert(docs, options, callback)

https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/collection.js#L71-91

答案 4 :(得分:12)

使用async parallel,您的代码如下所示:

  async.parallel([obj1.save, obj2.save, obj3.save], callback);

由于Mongoose中的约定与async(错误,回调)中的约定相同,因此您无需将它们包装在自己的回调中,只需在数组中添加保存调用即可在完成所有操作后获得回调

如果使用mapLimit,则可以控制要并行保存的文档数。在此示例中,我们将并行保存10个文档,直到所有项目都成功保存为止。

async.mapLimit(myArray, 10, function(document, next){
  document.save(next);
}, done);

答案 5 :(得分:8)

我知道这是一个老问题,但它让我担心这里没有正确答案。大多数答案只是讨论迭代所有文档并单独保存每个文档,如果您有多个文档,这是一个不好的想法,并且在许多请求中甚至会重复该过程。

MongoDB专门用于插入多个文档的batchInsert()调用,这应该从本机mongodb驱动程序中使用。 Mongoose是基于此驱动程序构建的,它不支持批量插入。它可能是有道理的,因为它应该是MongoDB的Object文档建模工具。

解决方案:Mongoose附带本机MongoDB驱动程序。您可以通过要求它require('mongoose/node_modules/mongodb')来使用该驱动程序(对此不太确定,但如果它不起作用,您可以再次安装mongodb npm,但我认为应该这样做)然后做一个正确的{{1 }}

答案 6 :(得分:7)

较新版本的MongoDB支持批量操作:

var col = db.collection('people');
var batch = col.initializeUnorderedBulkOp();

batch.insert({name: "John"});
batch.insert({name: "Jane"});
batch.insert({name: "Jason"});
batch.insert({name: "Joanne"});

batch.execute(function(err, result) {
    if (err) console.error(err);
    console.log('Inserted ' + result.nInserted + ' row(s).');
}

答案 7 :(得分:5)

这是另一种不使用其他库的方法(不包括错误检查)

function saveAll( callback ){
  var count = 0;
  docs.forEach(function(doc){
      doc.save(function(err){
          count++;
          if( count == docs.length ){
             callback();
          }
      });
  });
}

答案 8 :(得分:2)

您可以使用mongoose save返回的承诺,mongoose中的Promise并不是全部,但您可以使用此模块添加该功能。

创建一个增强mongoose承诺的模块。

var Promise = require("mongoose").Promise;

Promise.all = function(promises) {
  var mainPromise = new Promise();
  if (promises.length == 0) {
    mainPromise.resolve(null, promises);
  }

  var pending = 0;
  promises.forEach(function(p, i) {
    pending++;
    p.then(function(val) {
      promises[i] = val;
      if (--pending === 0) {
        mainPromise.resolve(null, promises);
      }
    }, function(err) {
      mainPromise.reject(err);
    });
  });

  return mainPromise;
}

module.exports = Promise;

然后将它与mongoose一起使用:

var Promise = require('./promise')

...

var tasks = [];

for (var i=0; i < docs.length; i++) {
  tasks.push(docs[i].save());
}

Promise.all(tasks)
  .then(function(results) {
    console.log(results);
  }, function (err) {
    console.log(err);
  })

答案 9 :(得分:1)

使用insertMany功能插入许多文档。这只向服务器发送一个操作,Mongoose在点击mongo服务器之前验证所有文档。默认情况下,Mongoose按照它们在数组中的顺序插入项目。如果您没有维护任何订单,请设置ordered:false

重要 - 错误处理:

当组中发生ordered:true验证和错误处理意味着如果一个失败,一切都将失败。

单独进行ordered:false验证和错误处理时,将继续操作。错误将在一系列错误中报告。

答案 10 :(得分:0)

添加名为mongoHelper.js的文件

var MongoClient = require('mongodb').MongoClient;

MongoClient.saveAny = function(data, collection, callback)
{
    if(data instanceof Array)
    {
        saveRecords(data,collection, callback);
    }
    else
    {
        saveRecord(data,collection, callback);
    }
}

function saveRecord(data, collection, callback)
{
    collection.save
    (
        data,
        {w:1},
        function(err, result)
        {
            if(err)
                throw new Error(err);
            callback(result);
        }
    );
}
function saveRecords(data, collection, callback)
{
    save
    (
        data, 
        collection,
        callback
    );
}
function save(data, collection, callback)
{
    collection.save
    (
        data.pop(),
        {w:1},
        function(err, result)
        {
            if(err)
            {               
                throw new Error(err);
            }
            if(data.length > 0)
                save(data, collection, callback);
            else
                callback(result);
        }
    );
}

module.exports = MongoClient;

然后在您的代码更改中,您需要

var MongoClient = require("./mongoHelper.js");

然后是时候保存电话(连接并检索集合后)

MongoClient.saveAny(data, collection, function(){db.close();});

您可以根据需要更改错误处理,并在回调等中传回错误。

答案 11 :(得分:0)

这是一个老问题,但在搜索“mongoose insert files of documents”时谷歌搜索结果首先出现了。

您可以使用两个选项model.create()[mongoose]和model.collection.insert()[mongodb]。请在此处查看每个选项的优缺点:

Mongoose (mongodb) batch insert?

答案 12 :(得分:0)

以下是在Mongoose中直接使用MongoDB的Model.collection.insert()的示例。请注意,如果您没有这么多文档,比如少于100个文档,则不需要使用MongoDB的批量操作(see this)。

  

MongoDB还通过传递数组来支持批量插入   文档到db.collection.insert()方法。

var mongoose = require('mongoose');

var userSchema = mongoose.Schema({
  email : { type: String, index: { unique: true } },
  name  : String  
}); 

var User = mongoose.model('User', userSchema);


function saveUsers(users) {
  User.collection.insert(users, function callback(error, insertedDocs) {
    // Here I use KrisKowal's Q (https://github.com/kriskowal/q) to return a promise, 
    // so that the caller of this function can act upon its success or failure
    if (!error)
      return Q.resolve(insertedDocs);
    else
      return Q.reject({ error: error });
  });
}

var users = [{email: 'foo@bar.com', name: 'foo'}, {email: 'baz@bar.com', name: 'baz'}];
saveUsers(users).then(function() {
  // handle success case here
})
.fail(function(error) {
  // handle error case here
});