我有一种情况,我需要根据他们的职业来过滤用户,这是用户模式的定义方式:
const userSchema = new mongoose.Schema(
{
userData: {
professions: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Profession'
}
]
}
}
)
这是针对Professions模式的:
const ProfessionSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
trim: true,
}
}
)
如何获得具有ID5f8ea4396586f1168ab3a298
例如为ID的专业的用户列表?
我试过了
User.find({
"userData.professions": { $elemMatch: $in: ["5f8ea4396586f1168ab3a298"] }
})
但是似乎这与我要尝试的相反。当我根据5f8ea4396586f1168ab3a298
职业ID过滤结果时,需要得到这样的结果
[
{
"name": "John Doe",
"userData": {
"professions": ["5f8ea4396586f1168ab3a298", "5f8ea4226586f1168ab3a296"]
}
},
{
"name": "John Smith",
"userData": {
"professions": ["5f8ea4396586f1168ab3a298",]
}
},
{
"name": "Elon Musk",
"userData": {
"professions": ["5f8ea4466586f1168ab3a29a", "5f8ea4396586f1168ab3a298", "5f8ea4146586f1168ab3a295"]
}
}
]
你只需要使用即可将你的职业ID类型字符串转换为对象类型mongoose.Types.ObjectId
,第二次你错过了花{}
括号$elemMatch
,
let professions = ["5f8ea4396586f1168ab3a298"];
professions = professions.map(profession => mongoose.Types.ObjectId(profession));
User.find({
"userData.professions": { $elemMatch: { $in: professions } }
})
第二种选择,如果你要匹配一个专业,那么这是另一种选择,
let professions = "5f8ea4396586f1168ab3a298";
User.find({
"userData.professions": professions }
})