如何在MongoDB中检查用户ID是否存在于vote_user的数组字段中?
检查用户ID是否存在于vote_user下的任意数组字段中
方法一:用$or直接匹配多数组字段
你可以通过$or操作符同时校验vote_user下的所有数组字段,判断目标用户ID是否存在于任意一个数组内。示例代码如下:
const targetUserId = "要检查的用户ObjectId"; // 替换为实际ID,若为字符串需转成ObjectId:mongoose.Types.ObjectId(targetUserId) User.findOne({ $or: [ { "vote_user.cute": targetUserId }, { "vote_user.sweet": targetUserId }, { "vote_user.sexy": targetUserId } // 有更多数组字段就继续往$or数组里加 ] }) .then(user => { if (user) { console.log("该用户ID已存在于vote_user的某个数组中"); } else { console.log("该用户ID不在vote_user的任何数组里"); } }) .catch(err => { console.error("查询出错:", err); });
方法二:动态生成查询条件(字段较多时适用)
如果vote_user下的数组字段数量多,手动写$or条件太麻烦,可以先定义字段列表,再动态生成查询规则:
const targetUserId = "要检查的用户ObjectId"; const voteFieldList = ["cute", "sweet", "sexy"]; // 所有需要检查的数组字段 const orConditions = voteFieldList.map(field => ({ [`vote_user.${field}`]: targetUserId })); User.findOne({ $or: orConditions }) .then(user => { user ? console.log("用户ID已存在") : console.log("用户ID不存在"); }) .catch(err => console.error(err));
内容的提问来源于stack exchange,提问作者Epple
相关产品推荐
相关产品推荐

