【问题标题】:ExpressJs - Mongoose: Delete documents with Many To Many relationshipExpressJs - Mongoose:删除具有多对多关系的文档
【发布时间】:2021-08-23 19:47:16
【问题描述】:

我有两个具有多对多关系的模型,发布和标记。

发布架构:

const postSchema = new Schema(
  {
    user: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: [true, 'A post must belong to a user.'],
    },
    title: {
      type: String,
      unique: [true, 'A Post already exists with this title.'],
      required: [true, 'A Post must have a title.'],
    },
    slug: { type: String, unique: true },
    body: { type: String, required: [true, 'A Post must have a body.'] },
    coverImage: String,
    images: Array,
    isDraft: { type: Boolean, default: false },
    isPublished: { type: Boolean, default: false },
    tags: [{ type: Schema.Types.ObjectId, ref: 'Tag' }],
  },
  {
    timestamps: { currentTime: () => Math.floor(Date.now() / 1000) },
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
)

标签架构:

const tagSchema = new Schema(
  {
    title: { type: String, required: true },
    slug: { type: String },
    posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }],
  },
  {
    timestamps: { currentTime: () => Math.floor(Date.now() / 1000) },
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
)

现在我想在删除帖子时从标签文档中删除所有帖子的引用。

我正在尝试在 Post 模型中使用以下 remove 中间件,但它不起作用。帖子被删除,但标签文档上的引用仍然存在。

postSchema.pre('remove', function (next) {
  var post = this
  post
    .model('Tag')
    .update(
      { posts: { $in: post.tags } },
      { $pull: { posts: post._id } },
      { multi: true },
      next
    )
})

【问题讨论】:

    标签: express mongoose mongoose-schema


    【解决方案1】:

    在尝试了很多次之后,我终于摆脱了自己做错了什么。按照我为使其工作而进行的修复:

    在 Post Controller 中,我之前是这样做的:

    const post = await Post.findByIdAndDelete(req.params.id)
    

    我改成了:

    const post = await Post.findById(req.params.id)
    await post.remove()
    

    在后期模型中:

    postSchema.pre('remove', async function (next) {
      await this.model('Tag').updateMany(
        { posts: this._id },
        { $pull: { posts: this._id } },
        { multi: true },
        next
      )
    })
    

    【讨论】:

      猜你喜欢
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多