如何在mongoose / mongodb中按两个组合字段和引用字段过滤文档

时间:2019-10-12 10:09:34

标签: node.js mongodb mongoose

我有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而不是symbol,该如何按_id字段进行过滤?

对于第一个问题,我尝试使用$or运算符,但是它没有按预期运行。如果firstName = "John"surname = "Black"不能用于John Black过滤器$or

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

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

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

0 个答案:

没有答案