0

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.

Ameen Rashad
  • 514
  • 6
  • 17

2 Answers2

0

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.

chipadmin
  • 79
  • 9
  • No it can be accomplished in monk as I have shown, it just takes a little bit more work. Monk is lightweight, fast and awesome so in my case I can live with a bit more logic in my Javascript rather than a more functional driver. – chipadmin Dec 17 '14 at 01:56
0

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.

Community
  • 1
  • 1
Aleph Aleph
  • 5,215
  • 2
  • 13
  • 28