如何将记录插入到具有节点的mongodb中,其中记录具有$ oid

时间:2014-04-21 21:10:38

标签: javascript node.js mongodb mongoose

我是mongo和node的新手,我试图创建一个基本上类似于rails rake db:seed任务的脚本,其中我在特定文件夹中有一组.json文件,当我运行$ node seed时,它将运行我的seed.js文件,该文件将获取所有这些.json文件,并根据.json文件的文件名将内容插入到相应的mongo集合中。

基本上我运行$ node seed并执行/seed.js,查看/seeds/account.json,/ seeds/customer.json等。

这样我可以提交此代码,然后下一个开发人员可以运行$ node seed,他的mongo实例将填充一些数据来处理。

我遇到的问题是我获取的数据来自mongo中我的集合的转储,因此帐户的一些示例数据如下所示:

{ _id: { '$oid': '534d832177da4e0d38000001' },
  id: 1,
  name: something,
  dateTime: '2014-04-15T14:06:09-05:00' }

现在,当我运行$ node seed时,我收到此错误:

[Error: key $oid must not start with '$']

有没有办法解决此错误,或者我是否必须从所有.json文件中删除所有$oid

seed.js:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/testdb');
var dir = './seeds';
var db = mongoose.connection;

// Show connection error if there is one
db.on('error', console.error.bind(console, 'Database Connection Error:'));

// If we successfully connected to mongo
db.once('open', function callback() {

    var fs = require('fs'); // Used to get all the files in a directory

    // Read all the files in the folder
    fs.readdir(dir, function(err, list) {

        // Log the error if something went wrong
        if(err) {
            console.log('Error: '+err);
        }

        // For every file in the list
        list.forEach(function(file) {

            // Set the filename without the extension to the variable collection_name
            var collection_name = file.split(".")[0];
            var parsedJSON = require(dir + '/' + file);

            for(var i = 0; i < parsedJSON.length; i++) {

                // Counts the number of records in the collection
                db.collection('cohort').count(function(err, count) {
                    if(err) {
                        console.log(err);
                    }
                });

                db.collection(collection_name).insert(parsedJSON[i], function(err, records) {

                    if(err) {
                        console.log(err);
                    }

                    console.log(records[0]);
                    console.log("Record added as "+records[0]);

                });
            }

        });
    });
});

或者是否有任何已存在的图书馆用于此类任务?

4 个答案:

答案 0 :(得分:2)

http://docs.mongodb.org/manual/core/document/#field-names

字段名称不能以美元符号($)字符开头。

部分mongodb规范,因为它使用$来表示$ inc或$ unset等操作。

答案 1 :(得分:2)

所以有一个名为extended JSON syntax的东西更多的是规范,虽然某些驱动程序实现支持但尚未在节点本机驱动程序本身中实现。

虽然我知道有一个实现转换这些类型的实现,但在节点的jsontomongo模块中,并不严格支持所有类型。然而,可以清楚地看到in the code

'use strict';

module.exports = function (query) {
  var key, val;
  for (key in query) {
    if (!query.hasOwnProperty(key)) continue;
    val = query[key];
    switch (key) {
    case '$date':
      return new Date(val);
    case '$regex':
      return new RegExp(val, query.$options);
    case '$undefined':
      return undefined;
    }
    if (typeof val === 'object')
      query[key] = module.exports(val);
  }
  return query;
};

实施完整的规范或只需要ObjectId所需的内容将是一项相当简单的工作。您甚至可能希望自己将您的工作作为节点模块贡献。

因此,这实际上是解析解析JSON字符串所产生的对象结构所需的代码类型。

答案 2 :(得分:1)

使用此代替$ oid:

{ "_id" : ObjectId("5063114bd386d8fadbd6b004")}

答案 3 :(得分:0)

使用mongodb-extended-json npm扩展名:https://www.npmjs.com/package/mongodb-extended-json

以下是文档中的用法示例:

var EJSON = require('mongodb-extended-json');
var BSON = require('bson');

var doc = {
  _id: BSON.ObjectID(),
  last_seen_at: new Date(),
  display_name: undefined
};

console.log('Doc', doc);
// > Doc { _id: 53c2ab5e4291b17b666d742a, last_seen_at: Sun Jul 13 2014 11:53:02 GMT-0400 (EDT), display_name: undefined }

console.log('JSON', JSON.stringify(doc));
// > JSON {"_id":"53c2ab5e4291b17b666d742a","last_seen_at":"2014-07-13T15:53:02.008Z"}

console.log('EJSON', EJSON.stringify(doc));
// > EJSON {"_id":{"$oid":"53c2ab5e4291b17b666d742a"},"last_seen_at":{"$date":1405266782008},"display_name":{"$undefined":true}}

// And likewise, EJSON.parse works just as you would expect.
EJSON.parse('{"_id":{"$oid":"53c2ab5e4291b17b666d742a"},"last_seen_at":{"$date":1405266782008},"display_name":{"$undefined":true}}');
// { _id: 53c2ab5e4291b17b666d742a,
//   last_seen_at: Sun Jul 13 2014 11:53:02 GMT-0400 (EDT),