【发布时间】:2012-12-19 06:37:44
【问题描述】:
我正在尝试将 JSON 文件导入节点内的 MongoDB。这是我想要做的:
db.open(function(err, db) {
if(!err) {
db.collection('orgs', {safe: true}, function(err, collection) {
if (err) {
console.log("The 'orgs' collection doesn't exist. Creating it with sample data...");
db.collection('orgs', function(err, collection) {
orgs = require("../data/orgs.json");
collection.insert(orgs, {safe:true}, function(err, result) {});
});
}
});
}
});
请注意,NodeJS 可以自动将 JSON 导入为 JSON,这很好,但 JSON 不处理 ISODate 或 ObjectID 之类的对象。这是我尝试导入的 JSON 数据的片段:
./data/orgs.json:
{
"stub": "apple",
"name":"Apple, Inc.",
"timezone": "America/New_York",
"currency": "USD",
"plans": [
{"planId":1, "dtStart": {"$date":"2012-12-07 12:34:56"}},
{"planId":0, "dtStart": {"$date":"2012-12-05 23:45:02"}, "dtEnd": {"$date":"2012-12-07 12:34:56"}}
]
}
我正在为 Node 使用 mongodb 本机驱动程序。
我尝试使用整数表示日期,但它不起作用。
有没有办法用 MongoDB 识别的 JSON 表示 ISODate 和 ObjectID 字段?
【问题讨论】:
-
我们使用类似: import ejson from 'mongodb-extended-json';从'./fixtures/Animals.json'导入动物; ejson.deserialize(animals) 其中json就像
{ "_id" : { "$oid" : "54ebb..." }, "created" : { "$date" : "2015-02-23T23:19:54.674+0000" }}
标签: javascript json node.js mongodb node-mongodb-native