node.js - 如何组合 3 个集合 MongoDB?
问题描述
我有 3 个系列:餐厅、菜单和产品。
它们的结构:
我想用嵌套数组进行查询。并尝试:
const restaurant = await Restaurant.aggregate([
{
"$match": { _id: ObjectId(req.params.id) }
},
{
"$lookup": {
"from": "menus",
"localField": "menu",
"foreignField": "_id",
"as": "menu",
}
},
{
"$lookup": {
"from": "products",
"localField": "menu.products",
"foreignField": "_id",
"as": "menu.products"
}
},
])
但此查询返回没有菜单名称的数据:
"menu": {
"products": [
{
"_id": "604f349280a17606402211d3",
"price": 6,
"image": "https://i.pinimg.com/736x/00/67/1e/00671e890191ecfeaf680cbecd3acf3e.jpg",
"name": "Toast with banana",
"description": "210g, Composition: Bread, Nutella, Banana",
"user": "604f349280a17606402211d0",
"__v": 0,
"createdAt": "2021-03-15T10:18:58.220Z",
"updatedAt": "2021-03-15T10:18:58.220Z"
},...]
刚开始学习mongodb,所以不是很懂。请帮忙写一个请求。
如果我写错了,对不起,英语不是我的母语 :)
解决方案
原来是这样的
const restaurant = await Restaurant.aggregate([
{
"$match": { _id: ObjectId(req.params.id) }
},
{
"$lookup": {
"from": "menus",
"localField": "menu",
"foreignField": "_id",
"as": "menu",
}
},
{ "$unwind": { "path": "$menu", "preserveNullAndEmptyArrays": true } },
{
"$lookup": {
"from": "products",
"localField": "menu.products",
"foreignField": "_id",
"as": "menu.products"
}
},
{
"$group": {
"_id": "$_id",
"name": { "$first": "$name" },
"hours": { "$first": "$hours" },
"image": { "$first": "$image" },
"phones": { "$first": "$phones" },
"takeAway": { "$first": "$takeAway" },
"description": { "$first": "$description" },
"address": { "$first": "$address" },
"user": { "$first": "$user" },
"menu": { "$push": "$menu" }
}
}
])
推荐阅读
- python - TypeError:FUNCTION NAME () 缺少 1 个必需的位置参数:'v_air
- aspnetboilerplate - 无法访问已处置的对象 UserManagerProxy
- django - 让用户在 Django 中删除自己的帐户
- javascript - 没有更新时 React Hot Module Reload 刷新
- java - 在 dynamoDb 中查询全局二级索引
- latex - 如何为 wxMaxima 中的所有类型的分数设置 tex1 输出?
- java - 删除两个元素中的一个而不创建原始列表JAVA的副本
- amazon-web-services - Amazon EC2 无法访问在端口上运行的服务
- r - 使用 geojson_read 时出错 -- sp::CRS(SRS_string = from$wkt) : 未使用的参数 (SRS_string = from$wkt)
- python - 如何使用 Python 遍历整个 XML 文件