【问题标题】:Using $lookup from different collections on condition根据条件使用来自不同集合的 $lookup
【发布时间】:2019-03-29 17:48:58
【问题描述】:

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

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

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

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

【问题讨论】:

  • 目前无法使用查找来实现此功能,但如果您愿意,可以使用猫鼬填充方法来实现。如果你对 mongoose lemme 很好,我会发布答案
  • @PavanVora 感谢您的回复,如果您有任何答案,请发布。
  • dispatcherIdusersdrivers 集合中的公共字段。我说的对吗?
  • @AnthonyWinzlet 是的,它是 _id 字段表单驱动程序或用户
  • 您可能应该查看猫鼬文档中的Discriminators。而不是实际上有不同的“物理集合”,这基本上将事物放在同一个集合中,__t 字段表示“类型”。它基本上是多态性,因为您可以将不同的模式和方法抽象为“对象”,它们表现为不同的模型,但实际上存储在同一个集合中。从“MongoDB 的角度”来看,$lookup 基本上是在“单个集合”上完成的,并按“类型”过滤(如果需要),或者两者都不过滤。

标签: node.js mongodb mongoose


【解决方案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') 进行 mongoose 查询时,它将从调度程序文档中获取 dispatcherId 字段,并根据 type 字段中存储的值将 dispatcherId 值与集合 User 或 Driver 匹配。

【讨论】:

  • 感谢它对我有用。需要的字段如何投影?
  • refPath: "userType" 应该是 refPath: "type" 不是吗?
  • @Chathura 是的 refPath 将是相等的类型。并投影需要使用的字段可以将第二个参数作为字符串传递给填充方法,如 .populate('dispatcherId', 'username')。要选择更多项目,请在填充方法中传递空格分隔的字符串,例如电子邮件和电话传递第二个参数为“电子邮件电话”
猜你喜欢
  • 2019-10-05
  • 2021-01-25
  • 2022-07-14
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2021-10-25
相关资源
最近更新 更多