如何在Mongoose/Node.js中同时保存多个文档? [英] How can I save multiple documents concurrently in Mongoose/Node.js?

查看:305
本文介绍了如何在Mongoose/Node.js中同时保存多个文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此刻,我使用保存添加单个文档.假设我有一系列文档希望存储为单个对象.有没有一种方法可以通过单个函数调用将它们全部添加,然后在完成后获得单个回调?我可以单独添加所有文档,但是管理回调以解决所有问题.

At the moment I use save to add a single document. Suppose I have an array of documents that I wish to store as single objects. Is there a way of adding them all with a single function call and then getting a single callback when it is done? I could add all the documents individually but managing the callbacks to work out when everything is done would be problematic.

推荐答案

猫鼬尚未实现批量插入(请参见问题#723 ).

Mongoose doesn't have bulk inserts implemented yet (see issue #723).

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

Since you know the number of documents you're saving, you could write something like this:

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 太棒了.

This, of course, is a stop-gap solution and I would recommend using some kind of flow-control library (I use q and it's awesome).

这篇关于如何在Mongoose/Node.js中同时保存多个文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆