Mongoose Model#Aggregate函数返回0

时间:2018-09-06 00:50:28

标签: node.js mongodb mongoose aggregation-framework

我有以下对象:

  • 用户

  • 事件

  • 门票

  • 购票

我试图基于特定的Tickets计算给定TicketPurchases的所有EventTicket.type的数量。

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

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 is always 0

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

mLad

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

我还是mongodb的新手。预先感谢

工具:

  • Nodejs

  • 猫鼬

  • mLab

1 个答案:

答案 0 :(得分:2)

您错过了$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"}