Lee
Lee

Reputation: 2992

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

Upvotes: 1

Views: 238

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151122

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

Upvotes: 1

Related Questions