使用moment.max与mongoDB查询的结果时出错

我正在研究将文档插入到mongoDB集合中的nodeJS应用程序。 该文档具有一个createdAt字段,用于logging创build时间。 我也有一个function,logging查询的最新匹配到控制台。

码:

function getResult(player){ let timeList = []; MongoClient.connect(url, (err, db) => { if(err){ console.log(err); } else{ let count = db.collection('PokeBook').count({ 'player1': player }); //count function returns a promise count.then((val) => { db.collection('PokeBook').find({ 'player1': player }).forEach((doc) => { timeList.push(doc.createdAt); console.log(doc.createdAt); if(val===timeList.length){ myEmitter.emit('full', timeList); } }); }); } }); } //code for the emitter: myEmitter.on('full', (arr) => { console.log('full emitted'); console.log(moment.max(arr)); }); 

该代码返回一个错误说时刻[i] .isValid不是一个函数。 评论一下.max代码行就会成功地将“全面发射”logging到控制台。

任何build议,为什么会发生这种情况,以及如何解决这个问题将不胜感激。 🙂

moment.max()需要一个Moment对象数组,但是doc.createdAt (可能)是一个常规的Date对象。 您可以尝试replace:

 timeList.push(doc.createdAt); 

有:

 timeList.push(moment(doc.createdAt)); 

所以arr将是一个Moment对象的数组。

或者,您可以使用时刻自己实现max ,假设doc.createdAtDateNumber

 console.log(arr.sort()[arr.length-1]);