Mongoose查询role:USER文档后无法获取指定字段值如何解决
问题核心原因
userModel.find() 方法返回的是符合查询条件的Mongoose文档数组,而非单个文档实例,你之前的所有错误写法都是对数组直接操作,自然无法得到预期结果:
- 直接访问数组的
userName属性:数组本身没有该属性,返回undefined - 对数组调用
toObject():toObject()是单个Mongoose文档实例的方法,数组不存在该方法,因此报错 JSON.stringify(users).userName:JSON.stringify返回的是JSON字符串,字符串没有userName属性Document.prototype.toObject(users):toObject()是实例方法,不可通过原型静态传参调用
正确实现方案
方案1:查询直接返回普通JS对象(推荐)
如果不需要使用Mongoose文档的内置方法(如save()、update()等),直接在查询链上加.lean()方法,会直接返回普通JS对象数组,无需手动转换格式,性能更高:
const getUsersList = async () => { // 查询返回普通对象数组 const users = await userModel.find({ role: USER }).lean(); // 提取所有用户的userName字段 const userNameList = users.map(user => user.userName); // 取单个用户的字段 const firstUserName = users[0].userName; }
方案2:保留文档实例,手动转换
如果需要使用Mongoose文档的内置方法,对数组中的单个文档调用toObject()即可:
const getUsersList = async () => { const users = await userModel.find({ role: USER }).exec(); // 转换整个数组为普通对象数组 const plainUsers = users.map(doc => doc.toObject()); // 直接访问文档实例的字段也可正常读取 const firstUserName = users[0].userName; }
方案3:仅查询单个用户
如果你的需求本来就是查询单个符合条件的用户,使用findOne方法而非find,直接返回单个文档实例:
const getSingleUser = async () => { const user = await userModel.findOne({ role: USER }).lean(); if(user) { console.log(user.userName); } }
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

