我有一个Mongoose模式,我对该问题进行了一些简化:
const userSchema = Schema({
email: {
type: String,
required: true
},
profiles: [{
profileId: {
type: Schema.Types.ObjectId,
ref: 'Profile',
required: true
},
accessLevel: {
type: Number,
required: true
}
}],
})
我正在尝试通过accessLevel拟合时从Profile Mongoose对象中获取名称字段:类似
const profileNames = req.user.profiles.filter(p =>
p.accessLevel <= 2
).populate('profileId').map(p=>p.name)
但是显然这会引发错误。我将如何检索此信息?谢谢...
Rik
编辑:确定...这似乎可行,但并不理想:
const profiles = req.user.profiles.filter(f =>
f.accessLevel <= 2
).map(
p => {
return Profile.findById(p.profileId)
}
)
Promise.all(profiles).then(
profiles => {
profiles = profiles.map(
p => p.name
)
//=>Do stuff with profiles here
})
答案 0 :(得分:0)
好的,这似乎可行并且合理:
const profiles = req.user.profiles.filter(f =>
f.accessLevel <= 2
).map(
p => p.profileId
)
Profile.find({
"_id": {
$in: profiles
}
}).then(
profiles => {
profiles = profiles.map(
p => p.name)
//=>Do stuff with profiles here
})