【问题标题】:How to get data from one collection and insert into another collection in Nodejs?如何从一个集合中获取数据并插入到 Nodejs 中的另一个集合中?
【发布时间】:2017-11-22 16:23:15
【问题描述】:

我正在使用 Nodejs 和 MongoDB,我是 nodejs 的新手。我需要知道如何从一个集合中获取数据并附加一些额外的数据并插入到另一个集合中。

db.collection('collection1').find({ "Id" : 12345 }).toArray(function(err, result){ 
   db.collection('collection2', function(err, collection){
       collection.insert({
          //some data
       })
   })
})

当我尝试此代码时,它不起作用,它给我错误插入未定义。

谢谢, 约翰。

【问题讨论】:

  • 在大多数实际情况下,循环时需要控制回调。使用非常小的集合,您可以在插入时抛出整个数组。您可能应该使用“光标”而不是.toArray() 并处理它的每个结果。这取决于您在这里实际想要做什么,以及集合的大小。那部分不是很清楚。

标签: node.js mongodb express collections insert


【解决方案1】:
db.collection('collection1').find({ "Id" : 12345 }).toArray(function(err, result){ 
 //do the modification here 
 db.collection('collection2').insert(modifiedResult, function(err, result){
        if(err) {
            //log error
        }else{
            //log result
        }
    })
})

还有一件事,如果结果数组长度大于一个,并且你想单独插入,那么使用 promise

db.collection('collection1').find({ "Id" : 12345 }).toArray(function(err, result){ 
 //do the modification here 
  Promise.all(modifiedResult.map((eachModifiedResult)=>{
       return db.collection('collection2').insert(eachModifiedResult);
  }).then((result)=>{
      //result of the insert
  }).catch((err){
     //err if any happen
 });
})

但是,如果您有一个非常大的文档,请按照 Neil Said 的方式进行操作。使用游标一一读取集合并修改并插入到其他数据库中。

【讨论】:

  • 很确定问题是要求在此处插入 result 数组中的所有内容。看不出添加 if 和 else 真的有什么帮助。
  • 他是否能够插入文档。
【解决方案2】:

您可以使用回调库,如 async 或 Promises Q Promise

var collectionData = null;
var modifiedResult = null;

//这里我使用异步库来避免callbackHell

async.series([
    // for get data from collection 1.    
    function(cb) {
        var criteria = {
            "Id": 12345
        }
        db.collection('collection1').find(criteria).toArray(function(dbErr, dbResult) {
            if (err) {
                cb(dbErr)
            } else {
                collectionData = dbResult;
                cb()

            }
        })
    },
    // Append Data in collectionData
    function(cb) {

        // do you work here to append data in collectionData

        modifiedResult = extendedData; // this is just an example you need to work on it 
        cb();

    },
    // Update collection 2 here 
    function(cb) {
        db.collection('collection2').insert(modifiedResult, function(err, result) {
            if (err) {
                cb(dbErr)
            } else {
                collectionData = dbResult;
                cb()

            }
        });
    }

]);

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 2015-09-14
    • 2019-02-24
    • 2021-11-21
    • 2016-09-22
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多