首页 > 解决方案 > 添加与用户 ID 匹配的文档总数

问题描述

我正在尝试使总订单与单个用户匹配。

这是我的订单架构:

const OrderSchema = new Schema({
    lineItems: [{
        product: {
            type: Schema.Types.ObjectId,
            ref: "Product"
        },
        quantity: {
            type: Number
        }
    }],
    created_at: {
        type: Date,
        default: Date.now
    },
    user: [{
        type: Schema.Types.ObjectId,
        ref: "User",
        required: true
    }]
});

这是我的猫鼬查询:

getOrderTotal: function (req, res) {
    const userID = req.params.userid;
    Order
      .aggregate([
        { $match: { 'user': mongoose.Types.ObjectId(userID) } },
        {
          $lookup: {
            from: "products",
            localField: "lineItems.product",
            foreignField: "_id",
            as: "product"
          }
        },
        {
          $unwind: "$product",
        },
        {
          $unwind: "$lineItems"
        },
        {
          $group: {
            _id: mongoose.Types.ObjectId(userID),
            count: { $sum: 1 }

          }
        }
      ])
      .then(dbModel => res.json(dbModel))
      .catch(err => res.status(422).json(err));
  }

我测试的每个用户,count 字段总是返回一个 72 的值。db 中甚至没有总共 72 个订单。当我将 1 值更改为不同的数字时,它返回 72 的某个倍数,即 2 返回 144,0.5 返回 36。

标签: javascriptmongodbmongoose

解决方案


推荐阅读