Nodejs级联删除4张表

编程入门 行业动态 更新时间:2024-10-07 13:21:17

Nodejs<a href=https://www.elefans.com/category/jswz/34/1770595.html style=级联删除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);

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

回答如下:

更多推荐

Nodejs级联删除4张表

本文发布于:2024-05-30 09:05:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770330.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:级联   Nodejs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!