如何在Node.js中的MongoDB mapReduce函数中处理ISOdate戳

我在Node.js应用程序的mapReduce函数中使用了Date函数。 在下面的map函数中,我首先将ISOdatestring转换为Date对象。 然后获取date的年份,这将被用作关键。 预期的结果是输出集合中的_id是“2013”​​。 但实际上,_id是NaN(types是Double)。

看来在mapReduce函数内使用的Date函数与普通的JS Date函数不同。

  1. 我如何在下面的map函数中使用正常的JS Date函数?
  2. 如果不可能,如何在map函数内处理ISOdatestring?

var mongodb = require('mongodb'); var map = function() { var date = new Date("2013-03-19T08:27:58.001Z"); // Convert ISO date string to Date object var year = date.getFullYear(); // Get the year of the date. emit(year, this); }; var reduce = function(key, values) { if (values.length) { return values[0]; } }; /**Connect to MongoDB */ var server = new mongodb.Server(dbIP, dbPort, {}); var db = new mongodb.Db(dbName, server, {safe:true}); db.open(function (err, client) { if( err ) { console.log('DB: Failed to connect the database'); } else { console.log('DB: Database is connected'); db.collection(collectionName).mapReduce( map, reduce, { out: 'map_reduce_collection' } , function (err, collection, stats){ if( err ) { console.log('Map reduce: Fail.'); } else { console.log('Map reduce: Success.'); } db.close(); }); } }); 

=======编辑:添加解决scheme=========

ISODate解决了我的问题。 下面的代码适用于我。

 // The map and reduce functions are serialized by the driver and run in the MongoDB server. // The functions used in them should be supported by the mongo shell. // A tip is checking if a function is supported by map-reduce function by execuing it in the mongo shell. // For example, the Date function is different from the one supported by Node.js. // In Node.js, the var date = new Date("2013-03-19T08:27:58.001Z"); works. But it doesn't work in mongo shell. // So it can't be used in the map function. var map = function() { var date = new ISODate("2013-03-19T08:27:58.001Z"); var year = date.getFullYear(); emit(year, this); }; 

谢谢,杰弗里

在这里发表答案。

ISODate解决了我的问题。 下面的代码适用于我。

 // The map and reduce functions are serialized by the driver and run in the MongoDB server. // The functions used in them should be supported by the mongo shell. // A tip is checking if a function is supported by map-reduce function by execuing it in the mongo shell. // For example, the Date function is different from the one supported by Node.js. // In Node.js, the var date = new Date("2013-03-19T08:27:58.001Z"); works. But it doesn't work in mongo shell. // So it can't be used in the map function. var map = function() { var date = new ISODate("2013-03-19T08:27:58.001Z"); var year = date.getFullYear(); emit(year, this); };