Mongoose中find函数未直接返回数据库对象的问题求助
解决Mongoose登录查询返回嵌套对象的问题
你遇到的问题是因为Mongoose默认会把查询结果包装成Mongoose Document实例,这些实例自带了很多框架内置的方法和属性,而你需要的原始文档数据被存放在_doc属性中。下面给你几个直接拿到干净数据的解决方案:
1. 使用.lean()(推荐方案)
这是最简洁高效的方式,.lean()会告诉Mongoose跳过Document实例的包装过程,直接返回原始的JavaScript对象,这样就不会有_doc嵌套了:
schema.statics.LOGIN = async function(username, password) { // 因为用户名是unique的,用findOne更合适(返回单个用户而非数组) return await this.findOne({ username, password }).lean(); }
如果你的业务场景确实需要返回匹配的用户数组(虽然登录场景不太常见),可以保留find:
schema.statics.LOGIN = async function(username, password) { return await this.find({ username, password }).lean(); }
2. 手动提取_doc属性
如果你因为某些原因不能使用.lean(),可以手动从Document实例中提取_doc里的原始数据:
单个用户场景(用findOne)
schema.statics.LOGIN = async function(username, password) { const userDoc = await this.findOne({ username, password }); // 注意处理用户不存在的情况,避免报错 return userDoc ? userDoc._doc : null; }
多个用户场景(用find)
schema.statics.LOGIN = async function(username, password) { const userDocs = await this.find({ username, password }); // 遍历数组提取每个用户的原始数据 return userDocs.map(doc => doc._doc); }
补充说明
为什么原来的代码会返回嵌套对象?
Mongoose的find/findOne方法默认返回的是Mongoose Document对象,这个对象不仅包含你的文档数据,还集成了Mongoose的操作方法(比如save()、updateOne()等),这些额外的属性和方法导致了层级嵌套,而真实的业务数据就被放在_doc这个属性里。
内容的提问来源于stack exchange,提问作者Yedidya kfir
相关产品推荐
相关产品推荐

