【问题标题】:Error when using moment.max with the results of a mongoDB query将 moment.max 与 mongoDB 查询的结果一起使用时出错
【发布时间】:2017-05-08 07:26:08
【问题描述】:

我正在开发一个将文档插入 mongoDB 集合的 nodeJS 应用程序。该文档有一个 createdAt 字段,用于记录创建时间。我还有一个函数可以将查询的最新匹配记录到控制台。

代码:

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

代码返回一个错误,指出 moment[i].isValid 不是函数。注释 moment.max 代码行会成功将“full emit”记录到控制台。

任何关于为什么会发生这种情况以及如何解决这个问题的建议将不胜感激。 :)

【问题讨论】:

    标签: node.js mongodb momentjs


    【解决方案1】:

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

    timeList.push(doc.createdAt);
    

    与:

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

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

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

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

    【讨论】:

    • 这次返回不同的错误:locale.longDateFormat is not a function。
    • doc.createdAttypeof 是什么?此外,我已经用另一个选项更新了我的答案。
    • 它们是瞬间对象。我更改了代码以生成 Date 对象,然后使用了您的第一种方法,该方法效果很好。谢谢! :)
    猜你喜欢
    • 2021-12-12
    • 2021-06-10
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多