获取Mongoose错误:参数必须是聚合管道运算符

时间:2017-03-30 19:43:38

标签: node.js mongodb mongoose

我试图运行此聚合但我无法通过聚合选项参数获得结果,有什么问题?这是我的汇总:

 var  coupons = couponModel.aggregate(
        [
            {
                "$lookup": {
                    from: "campaigns",
                    localField: "campaignId",
                    foreignField: "_id",
                    as: "campaigns"
                }
            },
            { "campaignId": { "$in": campaignsIds } },
        ],
        {
            allowDiskUse: true,
            explain: true
        }
    );

也尝试不同的结构:

 couponModel.aggregate(
        [
            {
                "$lookup": {
                    from: "campaigns",
                    localField: "campaignId",
                    foreignField: "_id",
                    as: "campaigns"
                }
            },
            { "campaignId": { "$in": campaignsIds } },
        ],
        function(err,result) {
            if (err) return handleError(err);
            // Result is an array of documents
            console.log(result);
        }
    )

1 个答案:

答案 0 :(得分:1)

使用mongoose时,无法将对象作为aggregate()的第二个参数传递。相反,你必须使用mongoose函数。此外,在管道的第二个对象中,您忘记指定聚合阶段。所以你的代码看起来像这样:

var  coupons = couponModel.aggregate(
        [
            {
                "$lookup": {
                    from: "campaigns",
                    localField: "campaignId",
                    foreignField: "_id",
                    as: "campaigns"
                }
            },
            { $match: { "campaignId": { "$in": campaignsIds } } }
        ]
    )
    .allowDiskUse(true)
    .explain(true);