2

ノード内の MongoDB に JSON ファイルをインポートしようとしています。これが私がやろうとしていることです:

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.js には mongodb ネイティブ ドライバーを使用しています。

日付の整数表現を使用しようとしましたが、うまくいきませんでした。

MongoDB が認識する JSON で ISODate および ObjectID フィールドを表す方法はありますか?

4

2 に答える 2

3

You can't store dates and other custom objects in JSON, since in supports only Strings, Numbers, Booleans and null's. So, to load them from JSON you shall somehow restore them from their string representation. Of course, you can use BSON instead of JSON since it supports all this data types, but there is a better way to solve your problem.

Since your already using require instead of JSON.parse to load and parse your JSON data, you can make one more step and use JavaScript representation of your data instead of pure JSON:

var ObjectID = require('mongodb').ObjectID;

module.exports = {
  stub: "apple",
  name: "Apple, Inc.",
  timezone: "America/New_York",
  currency: "USD",
  plans: [
    {
      planId: new ObjectID("1"),
      dtStart: new Date("2012-12-07 12:34:56")
    },
    { 
      planId: new ObjectID("0"),
      dtStart: new Date("2012-12-05 23:45:02"),
      dtEnd: new Date("2012-12-07 12:34:56")
    }
  ]
}

In this case you'll be able to use new Date and new ObjectID to create dates and object ids.

N.B. You can use require('bson').ObjectID instead of require('mongodb').ObjectID, the result will be the same.

于 2013-01-04T20:08:00.087 に答える
2

次のようなものを使用します。

    import ejson from 'mongodb-extended-json';
    import animals from './fixtures/Animals.json';
    const array = ejson.deserialize(animals)

jsonはどこに似ていますか

{ "_id" : { "$oid" : "54ebb..." }, "created" : { "$date" : "2015-02-23T23:19:54.674+0000" }}

于 2019-12-04T17:27:30.820 に答える