如何在Mongoose中通过多属性查询数据,判断指定用户是否存在于团队中
MongoDB多字段任意匹配查询实现方案
你原有写法的问题在于使用了JavaScript原生的||逻辑运算符,该运算会在JS运行时直接返回第一个非空的查询对象,最终只有第一个{userID1:message.author.id}条件会被传入MongoDB执行,无法实现三个字段任意匹配的需求。
正确实现需要使用MongoDB内置的$or逻辑操作符,写法如下:
exports.start = async (message) => { const check = await group.find({ $or: [ { userID1: message.author.id }, { userID2: message.author.id }, { userID3: message.author.id } ] }) console.log(check); }
如果你仅需要判断用户是否存在于任意团队中,不需要获取完整的团队文档,使用exists()方法性能更高:
exports.start = async (message) => { const isUserExist = await group.exists({ $or: [ { userID1: message.author.id }, { userID2: message.author.id }, { userID3: message.author.id } ] }) // isUserExist为布尔值,true代表存在匹配记录,false代表不存在 console.log(isUserExist); }
结构优化建议
你当前的团队数据结构把用户信息拆分为独立的userID1/2/3、userName1/2/3字段,扩展性很差,如果后续团队人数调整需要修改表结构,更合理的设计是将用户存储为数组格式:
{ "_id" : ObjectId("6173107fcf643f15e1fced83"), "users": [ {"userId": "769819933390667796", "userName": "Davion"}, {"userId": "247276609894219777", "userName": "Davion"}, {"userId": "898413310872006716", "userName": "Davion"} ], "team" : "3", "__v" : 0 }
该结构下的查询代码更简洁:
const check = await group.find({ "users.userId": message.author.id })
内容的提问来源于stack exchange,提问作者Zjeref
相关产品推荐
相关产品推荐

