使用Mongoose查询返回新_id而非数据库存储值的问题咨询
Mongoose查询返回新_id而非原文档的问题解决
问题原因
你执行的const query = await UserType({type: 'User'});并不是数据库查询操作——直接调用Mongoose模型构造函数(即使省略new关键字),本质是实例化一个全新的未保存文档对象。Mongoose默认会为新文档自动生成_id,所以你拿到的是一个本地新创建的文档,而非数据库中存储的原有数据。
正确获取原文档的方法
要从数据库中读取已有文档,必须使用Mongoose提供的查询方法,常用的有以下两种:
1. 查询单个匹配文档(findOne)
用findOne方法精准匹配符合条件的单个文档:
const userType = await UserType.findOne({ type: 'User' }); console.log(userType); // 此时返回的文档会包含数据库中存储的原_id:6480989a8e96e5da4f9c8488
2. 查询多个匹配文档(find)
如果需要获取所有符合条件的文档,使用find方法返回文档数组:
const userTypes = await UserType.find({ type: 'User' }); console.log(userTypes); // 返回包含匹配文档的数组,每个文档都带有数据库中原有的_id
额外说明
- Mongoose模型作为构造函数,只有在配合
save()方法时才会将新文档写入数据库,比如:const newUserType = new UserType({ type: 'Guest' }); await newUserType.save(); // 此时新生成的_id会被存入数据库 - 若要避免Mongoose自动生成
_id,可以在Schema中显式关闭该特性:const user_types_Schema = new Schema({ type: String, _id: false // 禁用自动生成_id }, {versionKey: false});
内容的提问来源于stack exchange,提问作者Wahalez
相关产品推荐
相关产品推荐

