猫鼬中的$ match不会查询汇总字段

时间:2019-08-05 17:21:39

标签: javascript node.js mongodb mongoose

我正在尝试从另一个集合的字段中查询:

const Order = require("../../models/orders");
const User = require("../../models/user");

module.exports = {
  async list(req, res) {
    const { page = 1, limit = 10 } = req.query;

    let filters = req.query;

    filters = {
      ...filters,
      page: undefined,
      limit: undefined
    };

    const myAggregate = Order.aggregate([
      {
        $lookup: {
          from: "users",
          localField: "user",
          foreignField: "_id",
          as: "user"
        }
      },
      {
        $unwind: "$user"
      },
      {
        $match: { ...filters }
      },
      {
        $project: {
          coupon: 1,
          status: 1,
          "user._id": 1,
          "user.firstName": 1,
          "user.lastName": 1,
          currency: 1,
          rate: 1,
          amount: 1,
          subtotal: 1,
          total: 1,
          recipient: 1,
          createdAt: 1
        }
      }
    ]);

    const orders = await Order.aggregatePaginate(myAggregate, { page, limit });

    return res.send(orders);
  }
};

我正在使用一个名为mongoose-aggregate-paginate-v2的插件,但它只是向猫鼬数组添加了分页功能,所以问题出在$match上。

集合Orders存储此对象:

{
    "_id" : ObjectId("5d447d49a910461fd3b5e155"),
    "coupon" : [],
    "status" : "Processing",
    "user" : ObjectId("5d35f67f1cf34e0018e36d69"),
    "currency" : "BRL",
    "rate" : 10640,
    "amount" : 30,
    "subtotal" : 30,
    "total" : 30,
    "recipient" : ObjectId("5d404b39f005f70419d89ae3"),
    "createdAt" : ISODate("2019-07-30T13:59:48.532Z")
}

在汇总后,哪个变为:

{
  "docs": [
    {
      "_id": "5d447d49a910461fd3b5e155",
      "coupon": [],
      "status": "Processing",
      "user": {
        "_id": "5d35f67f1cf34e0018e36d69",
        "firstName": "Boo",
        "lastName": "Foo"
      },
      "currency": "BRL",
      "rate": 10640,
      "amount": 30,
      "subtotal": 30,
      "total": 30,
      "recipient": "5d404b39f005f70419d89ae3",
      "createdAt": "2019-07-30T13:59:48.532Z"
    }
  ],
  "totalDocs": 1,
  "limit": 10,
  "page": 1,
  "totalPages": 1,
  "pagingCounter": 1,
  "hasPrevPage": false,
  "hasNextPage": false,
  "prevPage": null,
  "nextPage": null
}

docs内是mongoose返回的数组。如果我对任何Orders字段进行查询,则查询将返回成功,仅返回与查询相对应的数据。但是,如果我尝试查询firstName,则无论我如何格式化$match,查询都是一个空数组。

我应该如何查询汇总字段?

0 个答案:

没有答案