在mongodb中插入json文件,指定要用作_id的密钥
我有一些json,它已经有一个ID,我想插入到我的mongo db中。 json是这样的在mongodb中插入json文件,指定要用作_id的密钥,json,node.js,mongodb,express,Json,Node.js,Mongodb,Express,我有一些json,它已经有一个ID,我想插入到我的mongo db中。 json是这样的 {"id" : 538748, "event_date":"2016-07-02", "name" : "Tim"} 插入时有没有办法将“id”映射到mongo的_id router.get('/newpage', function (req, res) { var db = req.db; var collection = db.get('myDatabase'); request({
{"id" : 538748,
"event_date":"2016-07-02",
"name" : "Tim"}
插入时有没有办法将“id”映射到mongo的_id
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 to I specify the _id here
collection.insert(body);
}
});
});
您需要修改插入的
正文
文档,以便有效地将id
字段重命名为\u id
:
body._id = body.id;
delete body.id;
collection.insert(body);
但是,只使用有效字段构建新文档,并在过程中执行映射,通常更干净、更安全:
var doc = {
_id: body.id,
event_date: body.event_date,
name: body.name
};
collection.insert(doc);
谢谢你,我问了一位同事的朋友,他也这么说了!我昨晚刚刚用node和mongo赢得了我的“Hello world”徽章=]