【问题标题】:Node.Js Aggregate $match only if variable existsNode.Js 仅在变量存在时才聚合 $match
【发布时间】:2020-05-11 22:49:47
【问题描述】:

在我的数据库中,我有以下类型的数据:

{
        "_id": "xxx",
        "amount": 800,
        "title": "teste",
        "date": "2020-05-13T18:35:20.000Z",
        "paid": true,
        "type": "expense",
        "category": "debts_loans",
        "__v": 0
}

我有以下代码,用于汇总来自 mongoDB 数据库的数据。

const { initialDate, finalDate, paid = null } = req.query;

  try {
    const transactions = await Transaction.aggregate([
      {
        $match: {
          date: {
            $gte: new Date(initialDate),
            $lte: new Date(finalDate),
          },
        },
      }, ...

$match 聚合中,我只想聚合paid,除非它存在,否则我只想聚合date。我怎样才能做到这一点? url 参数paid 是可选的(可能是真的也可能不存在),这是反模式吗?



【问题讨论】:

  • 我不想只在存在的情况下汇总已付款 - 你的意思是在请求中存在吗?
  • 是的,存在于请求中。在数据库中它总是以真或假的形式存在。

标签: node.js mongodb express mongodb-query aggregation-framework


【解决方案1】:

在这种情况下,您需要根据paid 切换查询,如下所示:

const { initialDate, finalDate, paid } = req.query; // No need to make it null if it's not there in req.

let pipeline = [];

/** An if check prior to forming query */
paid == undefined ? 
    pipeline.push({ $match: { date: { $gte: new Date(initialDate), $lte: new Date(finalDate) } } }) : 
    pipeline.push({ $match: { paid: paid } })

try {
const transactions = await Transaction.aggregate(pipeline)
} catch () {}

【讨论】:

    猜你喜欢
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多