2

Node.js アプリケーションの mapReduce 関数で Date 関数を使用しています。以下の map 関数では、最初に ISO 日付文字列を Date オブジェクトに変換します。次に、キーとして使用される日付の年を取得します。期待される結果は、出力コレクションの _id が「2013」であることです。しかし、実際には _id は NaN (型は Double) です。

mapReduce 関数内で使用されている Date 関数が、通常の JS の Date 関数とは異なるようです。

  1. 以下のマップ関数内で通常の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 に答える