gpt4 book ai didi

node.js - 如何在 Node.js 的 MongoDB mapReduce 函数中处理 ISO 日期字符串

转载 作者:可可西里 更新时间:2023-11-01 10:44:24 26 4
gpt4 key购买 nike

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

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

  1. 如何在下面的 map 函数中使用普通的 JS 日期函数?
  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);
};

谢谢,杰弗里

最佳答案

在这里发布答案。

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

关于node.js - 如何在 Node.js 的 MongoDB mapReduce 函数中处理 ISO 日期字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15631986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com