I am making contact CRUD application with node.js, express and monogo. In my delete function, with the help of Postman I am able to delete contacts by ID, but if I try to delete by name or number I get an error saying:
path: ‘_id’,
“BSONError: input must be a 24 character hex string, 12 byte Uint8Array, or an integer at new ObjectId”
which tells me that it’s still searching for the ID even if I wanna find and delete by name and or number.
I tried taking the id field out of my code and I was able to search by name but if my code not my postman url has all 3 it doesnt work.
const deleteContact = async (req, res) => {
try {
const {
id: contactId,
Name: contactName,
Number: contactNumber
} = req.params;
let queryObject = {};
if (contactName) {
queryObject.Name = contactName;
}
if (contactId) {
queryObject._id = contactId;
}
if (contactNumber) {
queryObject.Number = contactNumber;
}
let contactDelete = await Contact.findOneAndDelete(queryObject);
if (!contactId && !contactName && !contactNumber) {
return res
.status(400)
.json({ msg: 'Please provide either an ID or a Name' });
}
res.status(200).json({
contactDelete,
message: `Contact deleted successfully!`
});
} catch (error) {
console.error('Error', error);
res.status(500).json({ msg: 'Server Error!' });
}
};