【问题标题】:How to pass the timestamp in the query param of NodeJS (Express + Mongoose)如何在 NodeJS 的查询参数中传递时间戳(Express + Mongoose)
【发布时间】:2021-03-24 06:23:09
【问题描述】:

我有这样的 MongoDB 命令:

db.transaction.aggregate([
   {
      "$match": 
         {
          $and:[{
                  'is_deleted': false,
                   'createdAt':{'$gte': ISODate('2020-09-01T00:00:00.000Z'),'$lte':ISODate('2020-12-15T00:00:00.000Z')}, 
                   'type': 'deposit'
                }
               ]
         }
         
   },
   {
       $group: {
          _id: null ,
          depositRevenue: {$sum: "$amount"}
        }
   }
]).pretty();

输出如下:

{
    "_id" : null,
    "depositRevenue" : 324
}

查询很好,但是当我传入 NodeJS 时它不起作用。 Bellow 是我在 ExpressJS 和 Mongoose 中的代码。

      let revenueData = await Transaction.aggregate([
       
        {
          $match: {
           $and: [{objFind}]
          }
        },
        {
          $group: {
            _id: null,
            totalRevenue: {$sum: "$amount"}
          }
        }
      ]);

objFind 像这样:

    var startDate = new Date(req.query.startDate).toISOString();
      var endDate = new Date(req.query.endDate).toISOString();
      var objFind = {};
      objFind["is_deleted"] = false;
      
      if(startDate != undefined || endDate != undefined){
        objFind["createdAt"] = {};
        if(startDate != undefined){
              objFind["createdAt"]["$gte"] = startDate;
        }
        if(endDate != undefined){
              objFind["createdAt"]["$lte"] = endDate;
        }
      }
       objFind['type'] = 'deposit';

请看一看。谢谢你

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework aggregate


    【解决方案1】:

    你需要简化你的代码,

    • 创建具有所需条件的对象
    var objFind = { 
        is_deleted: false,
        type: 'deposit'
    };
    
    • 检查可用的开始日期和结束日期
    if (req.query.startDate || req.query.endDate) {
        objFind.createdAt = {};
        if (req.query.startDate) objFind.createdAt.$gte = new Date(req.query.startDate);
        if (req.query.endDate) objFind.createdAt.$lte = new Date(req.query.endDate);
    }
    
    • 默认根字段条件为and条件,所以不需要使用$and
    let revenueData = await Transaction.aggregate([
        { $match: objFind },
        {
            $group: {
                _id: null,
                totalRevenue: { $sum: "$amount" }
            }
        }
    ]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 2014-04-23
      • 2013-12-19
      • 2019-10-17
      • 1970-01-01
      • 2015-08-26
      相关资源
      最近更新 更多