我正在尝试使用查找填充集合。事情是我需要在express js中使用猫鼬一次加入三个集合。 我有三个集合,分别是用户,技能,用户技能。
用户和UserSkills已连接。技能和用户技能已连接。但没有用户和技能。
我的模特很像
用户
{
_id: 5ec6d940b98e8f2c3cea5f22,
name: "test one",
email: "test@example.com"
}
技能
{
_id: 5ec786b21cea7d8c8c186a54,
title: "java"
}
用户技能
{
_id: 5ec7879c1cea7d8c8c186a56,
skillId: "5ec786b21cea7d8c8c186a54",
userId: "5ec6d940b98e8f2c3cea5f22",
level: "good"
}
我尝试了
user = await User.aggregate([{
$lookup: {
from: "userskills",
localField: "_id",
foreignField: "userId",
as: "userskills"
}
}, {
$unwind: {
path: "$userskills",
preserveNullAndEmptyArrays: true
}
}, {
$lookup: {
from: "skills",
localField: "userskills.skillId",
foreignField: "_id",
as: "userskills.skill",
}
}, {
$group: {
_id : "$_id",
name: { $first: "$name" },
skill: { $push: "$skills" }
}
}, {
$project: {
_id: 1,
name: 1,
skills: {
$filter: { input: "$skills", as: "a", cond: { $ifNull: ["$$a._id", false] } }
}
}
}]);
必填结果:
{
"users" : [
{
_id: "5ec6d940b98e8f2c3cea5f22"
name: "test one",
email: "testone@example.com",
"skills" : [
{
_id: "5ec7879c1cea7d8c8c186a56",
level: "good",
"skill" : {
_id: "5ec786b21cea7d8c8c186a54",
title: "java"
}
}
]
},
{
_id: "5ec6d940b98e8f2c3cea5f23"
name: "test two",
email: "testtwo@example.com",
"skills" : [
{
_id: "5ec7879c1cea7d8c8c186a57",
level: "good",
"skill" : {
_id: "5ec786b21cea7d8c8c186a55",
title: "php"
}
}
]
}
]
}
使用时
user = await User.find().populate('Skills").exec()
结果来了
{
"users" : [
{
_id: "5ec6d940b98e8f2c3cea5f22"
name: "test one",
email: "testone@example.com",
"skills" : [
{
_id: "5ec7879c1cea7d8c8c186a56",
level: "good",
skillId: "5ec786b21cea7d8c8c186a55"
}
]
}
]
}
问题是我需要还应该提取技能名称。请帮我解决这个问题。我正在用nodejs和mongodb编写后端API。
答案 0 :(得分:1)
您可以将第二个$lookup
嵌入为custom pipeline的一部分:
await User.aggregate([
{
$lookup: {
from: "userskills",
let: { user_id: "$_id" },
pipeline: [
{ $match: { $expr: { $eq: [ "$$user_id", "$userId" ] } } },
{
$lookup: {
from: "skills",
localField: "skillId",
foreignField: "_id",
as: "skill"
}
},
{ $unwind: "$skill" }
],
as: "skills"
}
}
])