I have two models Connection and Customer. The customer is referenced in Connection. I want to delete the customer from the customer document and remove or update the customer reference from the connection
the customer model is
const mongoose = require('mongoose')
const Customer = mongoose.model('Customer', {
cusName: {
type: String,
required: true,
trim: true
},
nic: {
type: String,
default: false
},
cNumber: {
type: String,
default: true
},
cBranch: {
type: String,
default: true
},
cAddress: {
type: String,
default: true
},
cEmail: {
type: String,
default: true
},
})
module.exports = Customer
and Connection model is
const mongoose = require('mongoose')
const Customer = mongoose.model('Customer', {
cusName: {
type: String,
required: true,
trim: true
},
nic: {
type: String,
default: false
},
cNumber: {
type: String,
default: true
},
cBranch: {
type: String,
default: true
},
cAddress: {
type: String,
default: true
},
cEmail: {
type: String,
default: true
},
})
module.exports = Customer
connection is again referenced by payment model currunly implemented delete operation as follows.
router.delete('/customer/:id', async (req, res) => {
try {
const customer = await Customer.findByIdAndDelete(req.params.id)
if (!customer) {
return res.status(404).send()
}
res.send(customer)
} catch (e) {
res.status(500).send()
}
})
CodePudding user response:
firstly add a customer Id field in connection
const mongoose = require('mongoose')
const Customer = mongoose.model('Customer', {
...
cusId: {
type: String,
required: true,
},
...
})
module.exports = Customer
and secondly, delete and the customers which have the same cusId
router.delete('/customer/:id', async (req, res) => {
try {
const customer = await Customer.findByIdAndDelete(req.params.id)
const connection = await Connection.deleteMany({ cusId: req.params.id })
if (!customer) {
return res.status(404).send()
}
res.send({ message: "User has been deleted" })
} catch (e) {
res.status(500).send()
}
})