Express Mongoose使用$pull删除数组子对象时触发类型重载报错
Mongoose
$pull 数组子项删除操作类型报错解决 场景说明
- 业务目标:对指定用户的experience文档执行更新,从内嵌的
experiences数组中删除_id为608c530de8ade5221b0e6d4e的子对象 - 对应数据库文档结构:
{ "_id": "608c3d353f94ae40aff1dec4", "userId": "608425c08a3f8db8845bee84", "experiences": [ { "designation": "Manager", "_id": "609197056bd0ea09eee9429c" }, { "designation": "Asst. Manager", "_id": "608c530de8ade5221b0e6d4e" }, { "designation": "Sr. Manager", "_id": "608c534be8ade5221b0e6d4f" }, ] }
- 模型定义代码:
const newExpSchema = new mongoose.Schema({ designation: { type: String, default: ""}, }); const experienceSchema = new mongoose.Schema({ userId: { type: String, required: true }, experiences: [newExpSchema], }); export default model("experience", experienceSchema);
- 控制器层更新逻辑:
const userId = req.userData.userId; const id = req.params.id; Experience.findOneAndUpdate( { userId: userId }, { $pull: { 'experiences': { '_id': id } }}, { multi:true }, function(err, obj) { // 后续业务逻辑 } );
- 触发的报错:
No overload matches this call.
Overload 1 of 3 .........
.......
The expected type comes from property '$pull' which is declared here on type 'UpdateQuery<Document<any, {}>>'
报错原因
- 类型不匹配:Mongoose 对数组内嵌套的子文档,会自动给每个子项生成
ObjectId类型的_id字段,但代码中从路由参数拿到的id是纯字符串类型,没有做类型转换,在TypeScript的类型校验阶段就无法匹配$pull操作的入参要求 - 冗余配置干扰:
findOneAndUpdate本身只匹配并更新单条文档,multi:true是updateMany方法的专属配置,传入该参数不会提升逻辑正确性,反而可能让类型推导出现偏差 - 类型推导缺失:
newExpSchema没有显式声明_id字段,Mongoose的类型推导工具无法识别数组子项存在_id字段,对$pull里的查询条件做校验时会判定字段不合法
修复方案
- 对路由传入的字符串
id做ObjectId类型转换,和数据库存储的子项_id类型保持一致 - 移除
findOneAndUpdate中冗余的multi:true配置 - (可选优化)在子Schema中显式声明
_id字段,完善类型推导规则
修复后的可运行代码:
// 引入Mongoose内置的ObjectId类型 const { Types } = require('mongoose'); const userId = req.userData.userId; // 将路由传入的字符串ID转换为Mongoose可识别的ObjectId类型 const targetExpId = new Types.ObjectId(id); Experience.findOneAndUpdate( { userId: userId }, { $pull: { 'experiences': { '_id': targetExpId } }}, function(err, obj) { if (err) { // 错误处理逻辑 } // 成功后的业务逻辑 } );
可选的模型优化写法(完善类型推导):
const newExpSchema = new mongoose.Schema({ // 显式声明子项_id字段,避免类型校验漏判 _id: { type: mongoose.Schema.Types.ObjectId }, designation: { type: String, default: ""}, });
内容的提问来源于stack exchange,提问作者ds97
相关产品推荐
相关产品推荐

