根据条件使用来自不同集合的$ lookup

时间:2019-03-29 07:43:07

标签: node.js mongodb mongoose

我有3个集合驱动程序,用户和调度程序。调度程序可以是驱动程序,也可以是用户,我的调度程序集合就是这样,

{
"_id" : ObjectId("5c9bb56a56f1a43e8aedf3c1"),
"dispatcherId" : ObjectId("5c3382fe3406281ba6863f7e"),
"type" : "driver",
"recordedTime" : ISODate("2019-03-27T17:39:54.030Z"),
"isEnable" : true,
"dispatchPackageType" : "commission",
"__v" : 0
}

dispatcherId来自驱动程序或用户集合。类型是“驱动程序”或“用户”。 我想写一个查询,如果类型是'drivers'$ lookup from drivers如果类型是user $ lookup from'users'。我实现了此功能,但找不到找到条件的方法。

Dispatcher.aggregate([{
    $match: {
        'type': 'driver'
    }
},{
            $lookup: {
                from: "drivers",
                localField: "dispatcherId",
                foreignField: "_id",
                as: "dispatcherDetails"
            }
        }, {
            $project: {
                'dispatcherDetails.otpPin': 0,
                'dispatcherDetails.saltSecret': 0,
                'dispatcherDetails.otpTime': 0
            }
        }
    ])

1 个答案:

答案 0 :(得分:1)

您可以在此处使用猫鼬模式的refType选项。我尝试通过示例向您解释refType

const mongoose = require('mongoose');

const dispatcherSchema = new mongoose.Schema({
  type: { type: String, enum: ["User", "Driver"] },
  dispatcherId: { type: mongoose.Schema.Types.ObjectId, refPath: "type" }
});
const Dispatcher = mongoose.model("Dispatcher", dispatcherSchema);


const userSchema = new mongoose.Schema({
    username: String
});
const User = mongoose.model('User', userSchema);


const driverSchema = new mongoose.Schema({
    drivername: String
});
const Driver = mongoose.model('Driver', driverSchema);

// Dispatcher.find().populate('dispatcherId'); this is just for your reference

在这里,我们有三个集合'User''Driver''Dispatcher'。现在,当您使用populate('dispatcherId')进行猫鼬查询时,它将从调度程序文档中获取dispatcherId字段,并根据存储在类型字段中的值将dispatcherId值与集合User或Driver相匹配。