【问题标题】:Mongoose Model#Aggregate function returning 0Mongoose 模型#聚合函数返回 0
【发布时间】:2019-02-11 04:25:17
【问题描述】:

我有以下物品:

  • 用户

  • 事件

  • 购票

我正在尝试根据特定的Ticket.type 计算给定Event 的所有TicketPurchases 中的Tickets 的数量。

我正在使用以下代码来尝试实现这一目标:

ticket.js

const TicketSchema = new Schema({
    type : {type: String},
    total_quantity : {type: Number},
    price : {type: String},
    limit_per_order: {type: Number},
    start_date: {type: Date},
    end_date: {type: Date},
    description: {type: String},
    validated: {type: String, default: 'false'}
});

ticketPurchase.js

const TicketPurchaseSchema = new Schema({
    user: {type: Schema.Types.ObjectId, ref: 'User'},
    event: {type: Schema.Types.ObjectId, ref: 'Event'},
    tickets: [{type: Schema.Types.ObjectId, ref: 'Ticket'}],
    time_stamp: {type: Date}

});

count.js

var event_id = req.query.event_id;
var ticket_id = req.query.ticket_id;

Ticket.findOne({ _id: ticket_id }).exec(function(err, results) {
  if (err) {
    console.log(err);
  }
  console.log(results); //returns ticket successfully
  TicketPurchase.aggregate(
    [
      {
        $match: {
          event: mongoose.Types.ObjectId(event_id)
        }
      },
      {
        $group: {
          _id: null,
          count: {
            $sum: {
              $size: {
                $filter: {
                  input: "$tickets",
                  as: "el",
                  cond: {
                    $eq: ["$$el.type", results.type]
                  }
                }
              }
            }
          }
        }
      }
    ],

    function(err, results) {
      if (err) {
        console.log(err);
      } else {
        console.log(results); //number of ticket purchases
      }
    }
  );
});

但我不断得到以下结果:

Count 始终为 0,但是,我可以确认 TicketPurchase 中有门票。

另外,this post 建议避免使用 $unwind。

我还是 mongodb 的新手。提前致谢

工具:

  • Nodejs

  • 猫鼬

  • mLab

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    您错过了$lookup 阶段,该阶段允许您将购票收集与门票收集结合起来。

    $match$group 之间添加以下阶段。

    {"$lookup":{
      "from":"ticket",
      "localField":"tickets",
      "foreignField":"_id",
      "as":"tickets"
    }}
    

    替代和更多performant 解决方案将使用$lookup + $unwind + $match 组合将类型标准应用于连接集合,而不是$group$filter。将$match 之后的所有阶段替换为以下阶段。

    类似

    {"$lookup":{
        "from":"ticket",
        "localField":"tickets",
        "foreignField":"_id",
        "as":"tickets"
    }},
    {"$unwind":"$tickets"},
    {"$match":{"tickets.type":results.type}},
    {"$count":"count"}
    

    【讨论】:

    • 现在我得到一个空数组作为结果
    • 您能否确保在查找阶段的from 属性中传递正确的集合名称?可能是tickets 而不是ticket
    • 天哪。就是这样。当它应该是ticketPurchase 中的数组名称时,我将其更改为ticketPurchase。非常感谢先生。非常感谢
    猜你喜欢
    • 2017-12-10
    • 2018-11-19
    • 2020-10-10
    • 2016-02-17
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    相关资源
    最近更新 更多