如何将logging插入到具有$ oidlogging的节点中

我是新来的mongo和节点,我正在尝试创build一个基本上类似于rake db:seed的脚本: 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的collections转储,因此帐户的一些示例数据如下所示:

 { _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]); }); } }); }); }); 

还是有任何已经存在的这类任务的图书馆?

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

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

mongodb规范的一部分,因为它使用$来表示像$ inc或$ unset这样的操作。

使用这个而不是$ oid:

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

所以有一种东西叫做扩展的JSON语法 ,它更像是一个规范,而某些驱动程序实现所支持的语法还没有在节点本地驱动程序本身中实现。

虽然我知道有一个实现转换这些types的实现,但在jsontomongo模块中,并不严格支持所有types。 然而, 在代码中可以清楚地看到:

 '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将是一个相当简单的练习。 你甚至可能想自己作为一个节点模块贡献自己的工作。

所以这实际上就是parsingJSONstring所产生的对象结构所需要的那种代码。