最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Nodejs级联删除4张表

网站源码admin42浏览0评论

Nodejs级联删除4张表

Nodejs级联删除4张表

我正在练习营地预订项目。我有 4 个表:Campbooking(Campgroun 信息)、Camp Appointment、Bus、Bus Appointment。我使用了 mongoose,并在 Campbooking、Camp Appointment、Bus、Bus Appointment 之间做了一些级联删除。除了巴士预约,一切看起来都很好。 EX) 当我删除露营预订 ID 101 时,我在 101 营地的营地预约被删除,我在 101 营地的巴士被删除,但我在所有营地的巴士预约被删除。我尝试修复它,但它让我在巴士预约露营预订部分“无效”。我应该如何修复我的代码:(

***** 这是我的 Campbooking 模型文件

const mongoose = require('mongoose');

const CampbookingSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, 'Please add campground name'],
        unique: true,
        trim: true,
        maxlength: [50, 'Name can not be more than 50 characters']
    },
    address:{
        type: String,
        required: [true, 'Please add campground address']
    },
    district:{
        type: String,
        required: [true, 'Please add campground district']
    },
    province:{
        type: String,
        required: [true, 'Please add campground province']
    },
    postalcode:{
        type: String,
        required: [true, 'Please add campground postalcode'],
        maxlength: [5, 'Postal Code can not be more than 5 digits']
    },
    tel:{
        type: String,
        required: [true, 'Please add campground tel']
    },
    region:{
        type: String,
        required: [true, 'Please add campground region']
    }
},{
    toJSON: {virtuals:true},
    toObject: {virtuals:true}
});

//Reverse populate with virtuals
CampbookingSchema.virtual('appointments', {
    ref: 'Appointment',
    localField: '_id',
    foreignField: 'campbooking',
    justOne: false
});

//Reverse populate with virtuals
CampbookingSchema.virtual('buses', {
    ref: 'Bus',
    localField: '_id',
    foreignField: 'campbooking',
    justOne: false
});

//Cascade delete appointments when a campbooking is deleted
CampbookingSchema.pre('Remove', async function(next){
    console.log(`Appointments being removed from campbooking ${this._id}`);
    await this.model('Appointment').deleteMany({campbooking: this._id});
    next();
});

//Cascade delete buses when a campbooking is deleted
CampbookingSchema.pre('Remove', async function(next){
    console.log(`Buses being removed from campbooking ${this._id}`);
    await this.model('Bus').deleteMany({campbooking: this._id});
    next();
});

//Cascade delete appointments when a campbooking is deleted
CampbookingSchema.pre('Remove', async function(next){
    console.log(`Bus Appointmet being removed from campbooking ${this._id}`);
    await this.model('BusAppointment').deleteMany({campbooking: this._id});
    next();
});

// Add custom remove method to the schema to avoid overwriting the internal remove method
CampbookingSchema.methods.Remove = async function() {
  await this.model('Campbooking').deleteOne({ _id: this._id });
};

module.exports = mongoose.model('Campbooking', CampbookingSchema);

*****这是我的巴士模型文件

const mongoose = require('mongoose');

const BusSchema = new mongoose.Schema({
    name:{
        type: String,
        required: [true, 'Please add bus name'],
        unique: true,
        trim: true,
        maxlength: [50, 'Name can not be more than 50 characters']
    },
    destination:{
        type: String,
        required: [true, 'Please add bus destination']
    },
    license:{
        type: String,
        required: [true, 'Please add bus license']
    },
    totalSeats:{
        type: Number,
        required: [true, 'Please add total number of seats']
    },
    bookedSeats:{
        type: Number,
        default: 0
    },
    campbooking:{
        type: mongoose.Schema.ObjectId,
        required: [true, 'Please add campbooking id']
    }
}, {
    toJSON: {virtuals:true},
    toObject:{virtuals:true}
});

BusSchema.virtual('availableSeats').get(function() {
  return this.totalSeats - this.bookedSeats;
});

BusSchema.virtual('busappointments',{
    ref:'BusAppointments',
    localField: '_id',
    foreignField: 'bus',
    justOne: false
});

//Cascade delete appointments when a campbooking is deleted
BusSchema.pre('Remove', async function(next){
    console.log(`Bus Appointments being removed from bus ${this._id}`);
    await this.model('BusAppointment').deleteMany({bus: this._id});
    next();
});

// Add custom remove method to the schema to avoid overwriting the internal remove method
BusSchema.methods.Remove = async function() {
    await this.model('Bus').deleteOne({ _id: this._id });
  };
  
module.exports = mongoose.model('Bus', BusSchema);

*****这是我的 BusAppointment 模型文件

const mongoose = require('mongoose');

const BusAppointmentSchema = new mongoose.Schema({
  apptDate: {
    type: Date,
    required: true
  },
  user: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
    required: true
  },
  bus: {
    type: mongoose.Schema.ObjectId,
    ref: 'Bus',
    required: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('BusAppointment', BusAppointmentSchema);

*****这是我的 Camp Appointment 模型文件

const mongoose = require('mongoose');

const AppointmentSchema = new mongoose.Schema({
  apptDate: {
    type: Date,
    required: true
  },
  user: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
    required: true
  },
  campbooking: {
    type: mongoose.Schema.ObjectId,
    ref: 'Campbooking',
    required: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('Appointment', AppointmentSchema);

任何人都可以帮助修复代码:)

回答如下:

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论