【问题标题】:mongoose query where id not in other model猫鼬查询其中 id 不在其他模型中
【发布时间】:2020-02-27 22:05:50
【问题描述】:

所以我有这种模型

const vetSchema = new mongoose.Schema({
    username: {type: String, required: true, trim: true, unique: true},
    email: {type: String, unique: true, trim: true,},
    expYear: {type: Number},
    KTP: {type: String, unique: true, trim: true},
    cert_id: {type: String, unique: true, trim: true, select: false},
})

const clinicSchema = new mongoose.Schema({
    vet: [{type: mongoose.Schema.Types.ObjectID, ref: 'vet'}],
)}

我要做的是通过用户名查找兽医,根据诊所ID,该兽医ID不包含在诊所中,查找兽医的查询是{username: {$regex: (?i)${keyword}.*}}

例如,我们有这个数据

Clinic = [{
    "_id" : ObjectId("5e57a45836d300b188f4444a"),
    "vet": [ObjectId("5e0742fc9d4b20100f89b626"),ObjectId("5e53698fd2b9ee43e7693e01")]
}]

Vet = [
{
    "_id" : ObjectId("5e0742fc9d4b20100f89b626"),
    "username": "VetClinic"
},
{
    "_id" : ObjectId("5e55df62576bc9811877033e"),
    "username": "VetNotClinic"
},
{
    "_id" : ObjectId("5e53698fd2b9ee43e7693e01"),
    "username": "VetClinic"
},
]

我想要的是如果我找到Vet 它只显示VetNotClinic 因为VetClinic 包含在诊所的ID 中,有什么好的查询/汇总吗?

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    您可以使用$nin 来查询字段“不在”这样的数组中的位置

    Vet.find({
    username: {$regex: (?i)${keyword}.*},
    _id: {$nin: clinic.vet}
    })
    

    【讨论】:

    • 所以你的意思是clinic是模特?
    • @ericanthony Clinic.vet 将是来自诊所集合/模型的特定诊所的兽医数组
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 2018-02-05
    • 2020-05-23
    • 2020-06-02
    • 1970-01-01
    • 2019-01-01
    • 2021-01-25
    相关资源
    最近更新 更多