Issue in inserting multiple documents (Bulk Insert) into a mongoDB collection using monk in Node.JS?

1.6k Views Asked by At

I am trying to insert multiple documents into a collection in mongoDB database, but am only getting only one object ID as response (multiple documents are getting created in the DB).

Code:

exports.createRelation = function(relationDoc, db, callback) {
var relations = db.get("relations");
relations
        .insert( relationDoc )
    .error( function ( err ) {
        callback(err, null);
    })
    .success( function ( doc ){
        callback(null, doc);
   });
};

in this the relationDoc would be an array

Input:

newRelDocs_Array:  [ { 
    path: [ 53d0b191c5ac61d403b0090d ] 
    tob: 1405343247 },
  { 
    path: [ 53d0b191c5ac61d403b0090d ],
    tob: 1405343247 } ]

Response :

createRelation(): Success
createRelation_db:  { 
  _id: 546a1d6f65c05d1c37660c4c,
  tob: 1405343247

}

FYI, I am using NodeJS, and connection to MongoDB with monk.

2

There are 2 best solutions below

1
On

In your question you say realationDoc is an array which I presume looks something like this:

realationDoc = [{
  id: 1,
  relation: 2
 },{
  id: 2, relation: 1
 }];

In monk, the insert function is not capable of the MonogoDB 2.4 built-in function Bulk Insert. See http://docs.mongodb.org/manual/reference/method/Bulk.insert/

With your code the way it is, you are creating a collection of a single document that has 2 fields, 1 the _id which is auto-generated and the second field that is your array.

To do what you want to do, you will need to modify your code like this:

for(var i = 0; i<relationDoc.length;i++){
  relations.insert(relationDoc[i])
  //..add promise code for success and error stuff
}

Probably not as efficient as the Bulk Insert provided in the native driver, but should get you to where you need to go with monk.

0
On

Monk collection wrapper provides access to the underlying collection object via .col field. You can use it to access the methods not implemented by Monk, such as bulk insert and aggregate:

var relations = db.get("relations");
var docs = [ { 
              path: [ "53d0b191c5ac61d403b0090d" ],
              tob: 1405343247
             }, {
              path: [ "53d0b191c5ac61d403b0090d" ],
              tob: 1405343247
             } ];
relations.col.insert(docs, callback);

Note that with .col you will not be able to use the promises functionality provided by monk, however. See here for more.