首页 > 解决方案 > 如何通过 mongoose/mongodb 中的两个组合字段和引用字段过滤文档

问题描述

我有模型PersonLanguage

const PersonSchema = new mongoose.Schema({
    photo: {
        type: String,
        default: "",
        trim: true
    },
    firstName: { 
        type : String, 
        default : '', 
        trim : true 
    },
    languagePairs: [{
        source: {
            type: Schema.Types.ObjectId, ref: 'Language'
        } ,
        target: {
            type: Schema.Types.ObjectId, ref: 'Language'
        }
    }],
    status: { 
        type : String, 
        default : '', 
        trim : true 
    },
    surname: {
        type: String,
        default: '',
        trim : true 
    }
})

const LanguageSchema = new mongoose.Schema({
    lang: { 
        type : String, 
        default : '', 
        trim : true 
    },
    icon: {
        type: String,
        default: '',
        trim: true
    },
    symbol:{
        type: String,
        default: '',
        trim: true
    }
})

如何persons按两个组合文件过滤fullName = firstName + surname?第二个问题是languagePairs.source如果我得到 filter assymbol但不是 as ,如何按字段过滤_id

对于第一个问题,我尝试使用$or运算符,但它没有按预期工作。如果firstName = "John"surname = "Black"过滤器John Black将无法与$or.

关于第二个问题 - 我目前找到的唯一解决方案是先找到 a languagesymbol然后将其_id用作过滤器:

const language = await Language.findOne({symbol});
const persons = await Person.find({'languagePairs.source': language.id})
    .populate('languagePairs.source')
    .populate('languagePairs.target')

我想找到一种解决方案,允许在一个查询中使用这些过滤器。这可能吗?实现它的最佳方法是什么?

标签: node.jsmongodbmongoose

解决方案


推荐阅读