首页 > 解决方案 > 如何使用 Mongoose 根据引用的子文档中的字段查询文档

问题描述

有两个模型:SupplierSupplierType-模型supplier_type上的字段Supplier包含ObjectId对相关supplier_type文档的引用。

我需要检索“面包师”的所有Suppliers位置Supplier.supplier_type.name

Supplier架构(为简洁起见):

const supplierSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 2,
    maxlength: 255,
  },
  ...
  supplier_type: { type: ObjectId, ref: 'SupplierType' },
});

Supplier Type架构:

const supplierTypeSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 2,
    maxlength: 50,
  },
  ...
});

一个典型的Supplier文档 -Supplier.supplier_type.populate()使用过的地方:

{
            ...
            "_id": "5e9604d45c18767097e00059",
            "name": "Benny's",
            "supplier_type": {
                "suppliers": [
                    "5e9604d45c18767097e00059"
                ],
                "_id": "5e8f7e2eca14f14e36785b8d",
                "name": "Bakers",
                "createdAt": "2020-04-09T19:57:34.731Z",
                "updatedAt": "2020-04-14T18:48:21.853Z",
                "__v": 0
            },
            ...
        },

询问:

const supplier = await SupplierType.aggregate([
      {
        $match: {
          name: 'Bakers',
        },
      },
      {
        $lookup: {
          from: 'supplier',
          localField: 'pk',
          foreignField: 'id',
          as: 'supplier',
        },
      },
      {
        $project: {
          supplier: 1,
        },
      },
    ])
    console.log('LOG: Supplier: ', supplier);
    if (!supplier) return res.status(404).send({ error: 'Supplier not found', code: 609 });

    res.send({ data: supplier });

回报:

{
    "data": [
        {
            "_id": "5e8f7e2eca14f14e36785b8d",
            "supplier": []
        }
    ]
}

标签: mongodbexpressmongoose

解决方案


推荐阅读