使用Mongoose的model.find()查询后无法读取返回值属性怎么办
问题原因
Mongoose 模型的find()方法返回值为符合查询条件的文档数组,即便仅有一条匹配数据,也会以数组形式包裹返回结果。你直接对数组类型的check变量读取userID属性,数组本身没有该属性,自然返回undefined。从你打印的结果也可以看到输出内容外层被[]包裹,验证了返回值是数组的结论。
解决方案
有两种常用修复方式,按需选择即可:
- 方案1:改用
findOne()方法查询单条数据findOne()会直接返回匹配到的单个文档对象,无需处理数组,修改查询代码即可:
// 把原来的find改成findOne let check = await profile.findOne({userID:message.author.id}); // 后续可以直接读取 check.userID
- 方案2:保留
find(),读取数组第一项的属性
如果业务需要使用find()做批量查询,可以取数组下标为0的元素读取属性,建议搭配可选链避免未查询到数据时抛出异常:
console.log(check[0]?.userID)
额外逻辑优化建议
你当前的代码没有做数据存在性判断,不管用户是否已经存在于数据库中都会直接走新增逻辑,当用户重复提交时会触发唯一键冲突报错。可以补充判断逻辑:
let check = await profile.findOne({userID:message.author.id}); if(check) { // 用户已存在,直接返回已加入提示即可 return message.channel.send(embedbuilder(`${message.author} 已经加入活动!`)) } // 不存在再走新增逻辑 try{ let userAdd = new profile({ userID: message.author.id, ServerID: message.guildId, level: 1, }); const savedUser = await userAdd.save(); message.channel.send(embedbuilder(`${message.author} has joined!`)) } catch(err) { message.channel.send(embedbuilder("Error joining the event")) }
内容的提问来源于stack exchange,提问作者Zjeref
相关产品推荐
相关产品推荐

