mongodb - 如何使用 Mongoose 根据引用的子文档中的字段查询文档
问题描述
有两个模型:Supplier
和SupplierType
-模型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": []
}
]
}
解决方案
推荐阅读
- python - 从静态网页获取特定项目时遇到问题
- sequelize.js - Sequelize migration - 定义一个空的 JSON 数组
- php - cURL 在 php shell_exec() 上没有按预期工作
- node.js - 如何使用 sequelize.js 保存从 FineOne 返回的关联?
- apache-spark - 我可以在没有中间解密文件的情况下在摄取到 HBase 的同时解密 HDFS 数据吗?
- javascript - Trying to enter a newline creates a comma instead
- powerbi - 两个矩阵列之间的差异出现两次(Power BI)
- php - 基于客户 ID 的 Woocommerce 订单 SQL 查询
- excel - 有没有更有效的方法来执行这个公共子公式?
- javascript - How to create a new array of set length from multiple arrays of varying length, the number of items taken from each smaller arrays based on importance