简体   繁体   中英

How to get data from one collection and insert into another collection in Nodejs?

Am using Nodejs and MongoDB and I am new to nodejs. I need to know how to get data from one collection and append some additional data and insert into another collection.

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

When I try this code its not working its giving me error insert is not defined.

thanks, John.

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
        }
    })
})

One more thing, If the result array length is more that one and you want to insert then separately then use 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
 });
})

But if you have a very large doc then do it as Neil Said. Read the collection one by one using cursor and modify them and insert them to other db.

You can use callback library like async or Promises Q Promise

var collectionData = null;
var modifiedResult = null;

// here i am using async library to avoid 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()

            }
        });
    }

]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM