首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

删除父级时,Mongoose删除子文档引用

在Mongoose中,当删除父级文档时,可以使用pre中间件和remove方法来删除子文档引用。

首先,我们需要定义父级文档的模式和子文档的模式。假设我们有一个父级文档Parent和一个子文档Child,它们之间通过ref字段建立引用关系。

代码语言:txt
复制
const mongoose = require('mongoose');

// 子文档模式
const childSchema = new mongoose.Schema({
  name: String
});

// 父级文档模式
const parentSchema = new mongoose.Schema({
  name: String,
  children: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Child' }]
});

const Child = mongoose.model('Child', childSchema);
const Parent = mongoose.model('Parent', parentSchema);

接下来,我们可以在父级文档模式中使用pre中间件来处理删除父级文档时的操作。在pre中间件中,我们可以使用remove方法来删除子文档引用。

代码语言:txt
复制
parentSchema.pre('remove', function(next) {
  // 删除子文档引用
  Child.remove({ _id: { $in: this.children } })
    .then(() => next())
    .catch(err => next(err));
});

现在,当我们删除父级文档时,Mongoose会自动触发pre中间件,并删除子文档引用。

代码语言:txt
复制
Parent.findById(parentId)
  .then(parent => {
    if (!parent) {
      throw new Error('父级文档不存在');
    }
    // 删除父级文档
    return parent.remove();
  })
  .then(() => {
    console.log('父级文档及其子文档引用删除成功');
  })
  .catch(err => {
    console.error(err);
  });

这样,当我们删除父级文档时,Mongoose会自动删除与之关联的子文档引用,确保数据的一致性。

推荐的腾讯云相关产品:腾讯云数据库 MongoDB,详情请参考腾讯云数据库 MongoDB

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的结果

领券