[英]How to find value inside array of object with mongoose?
我的事件系統對每個事件都有不同的角色(同一用戶在不同的事件中可能扮演不同的角色)。 我創建了用戶集合,這是我使用的模式:
const userSchema = new mongoose.Schema(
{
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
permissions: [{
eventId: { type: mongoose.Schema.Types.ObjectId, required: false, ref: 'Event' },
role: { type: String, required: false }
}]
},
{timestamps: true}
);
為了檢查是否允許用戶獲取此事件,我創建了中間件,它需要檢查 eventId 是否存在於“權限”下的用戶集合中
所以這是我創建的代碼:
const authorization = async (req, res, next) => {
try {
const eventId = req.params.id;
const token = req.headers.authorization.split(' ')[1]
const tokenDecoded = jwt.verify(token, process.env.JWT_SECRET);
const userId = tokenDecoded.id
console.log(userId)
const userPermissionCheck = await User.find({ _id: userId, 'permissions.eventId': { $in: eventId } } );
console.log(userPermissionCheck)
next();
} catch (error) {
res.status(401).json({ message: 'Auth failed.' })
}
}
我的問題是我在授權中間件中找到的 function 不工作......用 mongoose 在數組中搜索 object 的密鑰的正確方法是什么?
謝謝
從您的代碼看來您走在正確的軌道上,但您不需要 $in 運算符。 您應該能夠執行以下操作:
const userPermissionCheck = await User.find({ _id: userId, 'permissions.eventId': eventId });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.