【问题标题】:mongoose foreign key problem with node.jsnode.js 的猫鼬外键问题
【发布时间】:2020-06-03 17:41:47
【问题描述】:

我有 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({
 //
})

如何获取同一“公司”中“用户”的“叶子”列表

【问题讨论】:

  • 如果您提供了 json 格式的示例文档和预期的输出,那就太好了。还有你已经尝试了什么?

标签: node.js mongoose aggregation-framework


【解决方案1】:

我找到了解决办法:

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" }
    ])

【讨论】:

    猜你喜欢
    • 2019-09-16
    • 1970-01-01
    • 2018-08-18
    • 2018-03-04
    • 2020-03-26
    • 1970-01-01
    • 2012-08-12
    • 2013-12-03
    • 2019-02-09
    相关资源
    最近更新 更多