node.js - 如何在 MongoDB 中以 Catgepory > Sub Catgeory > Product 使用 nodejs 获取数据
问题描述
我有 3 个相互关联的不同模型,我想通过 ID 加入它们。我想要的回应如下
请在下面找到示例数据:
我想要这种类型的 json 作为响应
"categoryData": [
{
"_id": "5f227a756c42fe34e883be3c",
"categoryName": "Cake",
"categoryDescription": "Cake",
"IsActive": true,
"EnteredBy": null,
"WhenEntered": "2020-07-30T07:44:52.409Z",
"ModifiedBy": null,
"WhenModified": null,
"__v": 0,
"subcategorydata": [
{
"_id": "5f23c85d3926134528cb8208",
"categoryId": "5f227a756c42fe34e883be3c",
"subcategoryName": "SugerFree Cake",
"subcategoryDescription": "SugerFree Cake",
"IsActive": true,
"EnteredBy": null,
"WhenEntered": "2020-07-31T07:29:33.829Z",
"ModifiedBy": null,
"WhenModified": null,
"__v": 0,
"ProductData": [
{
"_id": "5f23c83e3926134528cb8207",
"ProductName": "Eggless Cake",
"ProductDescription": "Eggless Cake",
"IsActive": true,
"EnteredBy": null,
"WhenEntered": "2020-07-31T07:29:02.877Z",
"ModifiedBy": null,
"WhenModified": null,
"__v": 0
},
{
"_id": "5f23c83e3926134528cb8207",
"ProductName": "Eggless Cake",
"ProductDescription": "Eggless Cake",
"IsActive": true,
"EnteredBy": null,
"WhenEntered": "2020-07-31T07:29:02.877Z",
"ModifiedBy": null,
"WhenModified": null,
"__v": 0
},
}}
请在这方面帮助我。谢谢。
解决方案
请参阅MONGO 聚合查找
db.category.aggregate([
{
$lookup:
{
from: "subcategory",
localField: "_id",
foreignField: "categoryId",
as: "subcategory_items"
}
}
])
供进一步参考:多集合连接查询
推荐阅读
- apache-kafka - Kafka Streams with SpecificAvroSerde:如何配置反序列化异常处理程序
- flask-sqlalchemy - Flask 数据库 - 在类中添加图像作为默认值
- flutter - 锁滑向上颤振
- python - 使用 Python 在 PDF 中读取和写入 6000 页需要数小时
- azure - 从 azure 函数调用 azure 服务总线时如何解决 provider is null 错误
- google-apps-script - Google App 脚本:创建唯一的 RefNo,未从受保护的工作表中正确写入递增的新 refno,无法将前导零添加到 RefNo
- python - 如何删除图像opencv Python中的垂直线
- c++ - 将形状旋转到 1 到 2 弧度之间的任何位置都会重置其旋转
- angularjs - AngularJS 捕获图像网络摄像头
- c++14 - 我不明白“i”代表for循环内的索引