Mongoose查询中如何用$in匹配对象数组内的userName字段
问题原因
原写法中$in直接传入了user.team对象数组,无法和servicelog集合中字符串类型的execName字段匹配,需要先提取user.team数组内所有对象的userName字段,组成纯字符串数组后再传入$in。
修正后的代码
if(user.role === 'Admin' || user.managesAll === true) { // 展示所有文档 docQuery = ServiceLog.find().collation({ locale: 'en'}); } else if(user.isManager === true) { // 提取团队所有成员的userName组成字符串数组 const teamUserNames = user.team.map(member => member.userName); // $in可直接匹配数组内任意值,无需额外写$or,逻辑等价更简洁 docQuery = ServiceLog.find({ execName: { $in: [user.userName, ...teamUserNames] } }).collation({ locale: 'en' }); } else { // 普通用户仅展示自己的日志 docQuery = ServiceLog.find({ execName: user.userName }).collation({ locale: 'en' }); }
注意事项
请确认用户对象的用户名字段拼写是否正确,你的用户模型中定义的是驼峰格式userName,如果原代码中写的user.username是拼写错误,需要统一改为user.userName避免查询失效。
内容的提问来源于stack exchange,提问作者hemant
相关产品推荐
相关产品推荐

