You need to enable JavaScript to run this app. ExpressJs Mongoose多对多关联下删除文档同步清除关联引用问题
优惠活动
大模型
产品
解决方案
定价
更多

ExpressJs Mongoose多对多关联下删除文档同步清除关联引用问题

问题原因

  1. 查询Tag的筛选条件逻辑错误:你现有代码的筛选条件{ posts: { $in: post.tags } }完全错误,你需要筛选的是「posts数组中包含当前待删除Post的_id」的Tag文档,而不是匹配Tag的posts数组中是否存在Tag ID。
  2. Mongoose中间件触发规则限制:pre('remove')是文档中间件,只有你调用post.remove()这类实例方法删除文档时才会触发,如果你是用Post.findByIdAndDelete()、Post.deleteOne()这类静态方法删除Post,这个中间件不会执行。

修正后的代码

1. 修正原pre('remove')中间件

postSchema.pre('remove', function (next) {
  const post = this
  // 筛选条件调整为:所有posts数组包含当前post._id的Tag
  post.model('Tag').updateMany(
    { posts: post._id },
    { $pull: { posts: post._id } },
    next
  )
})

注:updateMany比带{multi: true}的update写法更清晰,是Mongoose官方推荐的批量更新写法

2. 补充适配静态删除方法的中间件

如果你项目中用的是findByIdAndDelete、deleteOne这类静态方法删除Post,需要额外添加对应查询中间件:

postSchema.pre('deleteOne', { document: true, query: false }, function(next) {
  const post = this
  post.model('Tag').updateMany(
    { posts: post._id },
    { $pull: { posts: post._id } },
    next
  )
})

postSchema.pre('findByIdAndDelete', async function(next) {
  // 先查询到待删除的post文档
  const post = await this.model.findOne(this.getQuery())
  // 删除关联的Tag引用
  await post.model('Tag').updateMany(
    { posts: post._id },
    { $pull: { posts: post._id } }
  )
  next()
})

验证注意点

  • 删除Post时优先调用实例方法post.remove(),可以确保中间件稳定触发
  • 如果使用静态删除方法,确保你已经添加了对应的查询中间件

内容的提问来源于stack exchange,提问作者Pranab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 05:24:06