2

我在 Node.js 应用程序的 mapReduce 函数中使用 Date 函数。在下面的 map 函数中,我首先将 ISO 日期字符串转换为 Date 对象。然后获取日期的年份,它将用作键。预期结果是输出集合中的 _id 为“2013”​​。但实际上,_id 是 NaN(类型是 Double)。

mapReduce 函数内部使用的 Date 函数似乎与普通的 JS Date 函数不同。

  1. 如何在下面的 map 函数中使用普通的 JS Date 函数?
  2. 如果不可能,如何处理map函数内部的ISO日期字符串?

.

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();
        });     
    }   
});

=======编辑:添加解决方案=========

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);
};

谢谢,杰弗里

4

1 回答 1

2

在这里发布答案。

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);
};
于 2013-05-31T09:31:36.287 回答