DELETE接口返回deletedCount=1删除成功 GET接口仍返回MongoDB已删文档
问题根因
- 核心错误:DELETE接口的查询字段不匹配
GET接口使用Products.findById(id)查询,本质是按MongoDB默认主键_id匹配文档,但DELETE接口的删除条件写的是{ id: id },而你的Product Schema中没有定义存储字段id,Mongoose默认的id是仅存在于文档对象的虚拟字段,无法用于数据库查询,所以删除操作根本没有命中你要删除的目标文档。 - DELETE接口返回逻辑错误
你当前的代码仅判断if(result)就返回删除成功,而Mongoose的deleteOne返回的result对象无论是否删除到文档都会存在,哪怕deletedCount为0也会返回成功提示,你误以为返回成功就是删除了目标文档。你提到的deletedCount: 1大概率是删除了其他带有自定义id字段的无关文档,目标文档实际仍存在于库中,所以GET接口可以正常返回。 - 其他可能原因
如果你确认目标文档确实已从MongoDB中删除仍能查询到,大概率是存在缓存:比如接口层配置了Nginx缓存、Redis缓存,删除操作后没有清理对应缓存,导致GET请求直接命中缓存返回旧数据;如果你的MongoDB部署了主从集群,也可能是写主库后读从库,主从同步延迟导致短时间内从库仍能查询到已删除文档。
修复方案
- 修正DELETE接口的删除条件与返回逻辑,两种修改方式二选一:
方式1:将deleteOne的查询条件改为匹配_id
方式2:直接使用Mongoose封装的exports.deleteDefinallySingleProduct = (req, res, next) => { let id = req.params.id; Products.deleteOne({ _id: id }).then(result => { if(result.deletedCount === 1) { res.status(200).json({ message: 'deleted_product', deletedCount: result.deletedCount }); } else { res.status(404).json({ message: 'product_not_found', id: id }) } }).catch(err => { res.status(500).json({ message: 'error_operation: ' + err }) }) }findByIdAndDelete方法exports.deleteDefinallySingleProduct = (req, res, next) => { let id = req.params.id; Products.findByIdAndDelete(id).then(result => { if(result) { res.status(200).json({ message: 'deleted_product' }); } else { res.status(404).json({ message: 'product_not_found', id: id }) } }).catch(err => { res.status(500).json({ message: 'error_operation: ' + err }) }) } - 缓存问题修复:如果存在接口缓存,删除产品成功后同步删除对应GET接口的缓存;如果是主从同步延迟问题,可对产品查询这类强一致性要求的请求配置强制读主库。
- 额外优化:你的GET接口中
populate('internalColor'),但Product Schema中没有定义internalColor关联字段,可按需补充Schema配置,避免无意义的关联查询。
内容的提问来源于stack exchange,提问作者A. Rizzi
相关产品推荐
相关产品推荐

