简体   繁体   中英

mongoose foreign key problem with node.js

I have 3 collections:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM