WHEN TWO COLLECTIONS LIKE USERS AND POSTS ARE IN A ONE TO MANY RELATION WHERE IF A USER'S ACCOUNT IS DELETED ALL THE POSTS CREATED BY THE USER ARE DELETED. THE PROCESS OF HANDLING THIS DELETION IS KNOWN AS HANDLING DELETION. IT IS BASICALLY CASCADING OF DELETION THAT PROPOGATES WITH USERS.
ANOTHER EXAMPLE: CUSTOMERS AND THEIR ORDERS ARE IN A ONE TO MANY RELATION,SO WHEN A CUSTOMER'S ACCOUNT IS DELETED ALL HIS ORDERS ARE DELETED.
// HANDLING DELETION USING MONGOOSE MIDDLEWARE
const mongoose = require("mongoose");
const { Schema } = mongoose;
main()
.then(() => {
console.log("connection successful");
})
.catch((err) => {
console.log(err);
});
async function main() {
await mongoose.connect("mongodb://127.0.0.1:27017/relations");
}
const orderSchema = new Schema({
item: String,
price: Number,
});
const customerSchema = new Schema({
name: String,
orders: [
{
type: Schema.Types.ObjectId,
ref: "Order",
},
],
});
const Order = mongoose.model("Order", orderSchema);
const Customer = mongoose.model("Customer", customerSchema);
const addUser = async () => {
let customer = new Customer({
name: "dhoni",
});
let order7 = new Order({
item: "WKgloves",
price: 777,
});
customer.orders.push(order7);
await customer.save();
await order7.save();
};
const findCustomer = async () => {
let res = await Customer.find({}).populate("orders");
console.log(res);
};
const delCust = async () => {
let res = await Customer.findByIdAndDelete("67cfc0b09261682212c77f3b");
console.log(res);
};
addUser();
findCustomer();
delCust();



HERE THE CUSTOMER'S DETAILS ARE DELETED BUT THE ORDERS ARE NOT.
SO WHEN THE delcust() IS CALLED, THE CUSTOMER'S ACCOUNT IS DELETED BUT NOT HIS ORDERS.
TO SOLVE THIS ISSUE MONGOOSE MIDDLEWARE IS USED.
WE HAVE 2 MIDDLEWARES PRE AND POST.
PRE- RUNS BEFORE EXECUTION
POST-RUNS AFTER EXECUTION.
HERE,WE WANT TO DELETE OUR ORDERS AFTER DELETION OF USER'S ACCOUNT,SO WE WILL BE USING POST.
IN MONGOOSE QUERY MIDDLEWARES THERE IS NO findByIdAndDelete()
IN MONGOOSE MIDDLEWARES WE HAVE findOneAndDelete.
WHENEVER findByIdAndDelete() IS CALLED IT TRIGGERS findOneAndDelete() WHICH TRIGGERS THE MONGOOSE MIDDLEWARE USED.(POST OR PRE)
HERE,WE DELETE ORDERS BASED ON CUSTOMER'S ID.SO, IF THE LENGTH OF CUSTOMER'S ORDER IS GREATER THAN 0, WE DELETE ALL THE ORDERS BY MATCHING THE ID OF ORDERS RELATED WITH THE CUSTOMER. WE USE in TO MATCH THE ORDER'S ID WITH THE CUSTOMER.
customerSchema.post("findOneAndDelete", async (customer) => {
// console.log(customer);
if (customer.orders.length) {
let res = await Order.deleteMany({ _id: { $in: customer.orders } });
console.log(res);
}
});
TOTAL CODE:
// HANDLING DELETION USING MONGOOSE MIDDLEWARE
const mongoose = require("mongoose");
const { Schema } = mongoose;
main()
.then(() => {
console.log("connection successful");
})
.catch((err) => {
console.log(err);
});
async function main() {
await mongoose.connect("mongodb://127.0.0.1:27017/relations");
}
const orderSchema = new Schema({
item: String,
price: Number,
});
const customerSchema = new Schema({
name: String,
orders: [
{
type: Schema.Types.ObjectId,
ref: "Order",
},
],
});
customerSchema.post("findOneAndDelete", async (customer) => {
// console.log(customer);
if (customer.orders.length) {
let res = await Order.deleteMany({ _id: { $in: customer.orders } });
console.log(res);
}
});
const Order = mongoose.model("Order", orderSchema);
const Customer = mongoose.model("Customer", customerSchema);
const addUser = async () => {
let customer = new Customer({
name: "dhoni",
});
let order7 = new Order({
item: "WKgloves",
price: 777,
});
customer.orders.push(order7);
await customer.save();
await order7.save();
};
const findCustomer = async () => {
let res = await Customer.find({}).populate("orders");
console.log(res);
};
const delCust = async () => {
let res = await Customer.findByIdAndDelete("67cfd2906aea8777a2cad2c5");
console.log(res);
};
// addUser();
// findCustomer();
delCust();



HERE ,THE CUSTOMER "dhoni" IS DELETED HIS ORDER"WKgloves" ARE ALSO DELETED.
Comments
Post a Comment