UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model "contact"

I am trying to update my contact in mongo db but running into this issue with CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model "contact"

Here is my controller function for updating a contact below

   const updateContact = async (req, res) => {
                const contact = await Contact.findById(req.params.id)
                if(contact) {
                    contact.phone_number = req.body.phone_number || contact.phone_number
                    contact.phone_type = req.body.phone_type || contact.phone_type
                    contact.group = req.body.group || contact.group
                    contact.firstName = req.body.firstName || contact.firstName
                    contact.lastName = req.body.lastName || contact.lastName
                    contact.company = req.body.company || contact.company
                    contact.email = req.body.email || contact.email

                    const updatedContact = await contact.save()

                    res.json({
                        _id: updatedContact._id,
                        phone_number: updatedContact.phone_number,
                        phone_type: updatedContact.phone_type,
                        firstName: updatedContact.firstName,
                        group: updatedContact.group,
                        lastName: updatedContact.lastName,
                        company: updatedContact.company,
                        email: updatedContact.email
                    })
                } else {
                    res.status(404)
                    throw new Error('Contact not found')
                }
            }


Read more here: https://stackoverflow.com/questions/68479412/unhandledpromiserejectionwarning-casterror-cast-to-objectid-failed-for-value

Content Attribution

This content was originally published by AmandaConda at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: