node.js - 如何通过 mongoose/mongodb 中的两个组合字段和引用字段过滤文档
问题描述
我有模型Person
和Language
:
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 language
,symbol
然后将其_id
用作过滤器:
const language = await Language.findOne({symbol});
const persons = await Person.find({'languagePairs.source': language.id})
.populate('languagePairs.source')
.populate('languagePairs.target')
我想找到一种解决方案,允许在一个查询中使用这些过滤器。这可能吗?实现它的最佳方法是什么?
解决方案
推荐阅读
- python - 为什么我的代码在列表中制作斐波那契序列时不起作用
- javascript - 测试字段是否为空而不是数字
- python - 在 pythonanywhere 上运行的 Slack Bot Python
- postgresql - 如何使用柴油进行 IN 查询?
- php - 我的 OpenGraph 不适用于 Discord、Twitter 和 Facebook 等任何社交媒体平台
- c# - 如何高效地处理数百个项目中的数千个 C# 文件?
- javascript - 使用 jQuery 进行复选框过滤
- mysql - MySQL Insert 如果不存在,否则返回 id
- macos - 在 Mac 上使用 Codelite 和 wxWidgets 但语言服务器不能 wx 包含
- amazon-web-services - 如何处理 DynamoDB boto3 的 batchwriteitem(在 lambda 中调用)跳过一些项目(不上传到 dynamodb)?