You need to enable JavaScript to run this app. Mongoose查询中如何用$in匹配对象数组内的userName字段
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 01:24:03