Search code examples
node.jsmongodbmonk

Save json into mongo with preselected ID


I receive JSON string from a web service.

{
    clientid: 123456,
    text: abc
}

I need to save this json into mongodb and use clientid as the _id field. How do I indicate that to nodejs? I'm using MONK


Solution

  • Really all you need to do in manipulate the object you get after parsing the JSON string:

      var db = require('monk')('localhost/test')
    , collection = db.get('example');
    
      var json = '{ "clientid": 123456, "text": "abc" }';
      var obj = JSON.parse( obj );
    
      obj._id = obj.clientid;
      delete obj.clientid;
    
      collection.insert( obj, function(err,doc) {
         // work in here
      });