如何使用Mongoose在引用的子文档中基于字段查询文档

时间:2020-04-20 19:37:11

标签: mongodb express mongoose

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

我需要检索所有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 });

1 个答案:

答案 0 :(得分:-1)

您可以尝试以下查询吗?这很可能是暂时的临时解决方案。检查这是否对您有用,因为这给了我预期的结果。

在以下link

上进行测试

  db.supplier_type.aggregate([
  {
    $match: {
      "name": "Bakers"
    }
  },
  {
    $lookup: {
      from: "supplier",
      localField: "id",
      foreignField: "supplier_type",
      as: "supplier"
    }
  },
  {
    $project: {
      supplier: 1
    }
  }
])

更新

这很可能是与ObjectId和字符串有关的问题。能行吗?

db.supplier_type.aggregate([
  {
    $match: {
      "name": "Bakers"
    }
  },
  {
    $addFields: {
      supplier_type_object: {
        $toObjectId: "$_id"
      }
    }
  },
  {
    $lookup: {
      from: "supplier",
      localField: "supplier_type",
      foreignField: "supplier_type_object",
      as: "supplier"
    }
  },
  {
    $project: {
      supplier: 1
    }
  }
])