node.js - Insert json file into mongodb specifying key to use as _id -


i have json has id want insert mongo db. json

{"id" : 538748,   "event_date":"2016-07-02",  "name" : "tim"} 

is there way map "id" mongo's _id when inserting?

router.get('/newpage', function (req, res) { var db = req.db; var collection = db.get('mydatabase');  request({     url: "http://someurl.com/json",     json: true }, function (error, response, body) {      if (!error && response.statuscode === 200) {         // how specify _id here         collection.insert(body);      } }); }); 

you need modify body doc you're inserting rename id field _id:

body._id = body.id; delete body.id; collection.insert(body); 

but it's typically cleaner , safer build new doc valid fields, performing mapping in process:

var doc = {     _id: body.id,     event_date: body.event_date,     name: body.name }; collection.insert(doc); 

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -