[英]mongoose foreign key problem with node.js
I have 3 collections:我有 3 个集合:
const LeaveSchema = new mongoose.Schema({
employee: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
})
const UserSchema = new mongoose.Schema({
company: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Company'
}
})
const CompanySchema = new mongoose.Schema({
//
})
How can i get list of "leaves" of "users" in the same "company"如何获取同一“公司”中“用户”的“叶子”列表
I find a solution:我找到了一个解决方案:
leaves = await Leave.aggregate([
{
"$lookup": {
"from": "users",
"let": { "companyId": "$employe" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$_id", "$$companyId"] } } },
{
"$lookup": {
"from": "companies",
"let": { "companyId": "$company" },
"pipeline": [
{ "$match": { "_id": new mongoose.Types.ObjectId(company_id),"$expr": { "$eq": ["$_id", "$$companyId"] } } }
],
"as": "companies"
}
},
{ "$unwind": "$companies" }
],
"as": "users"
}
},
{ "$unwind": "$users" }
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.