Estoy intentando a través de la solicitud PUT al servidor para actualizar un documento existente usando findOneAndUpdate(). el resultado de mi código es que se crea una réplica del documento original en lugar de actualizar el existente y se elimina el primer registro en la página.
app.put('/update', async (req, res) => { const { fullname, phone, country, img, title, id } = req.body const countryData = getCountryCodeByName(country) await Contact.findOneAndUpdate(id, { fullname, title, phone, country, img, countryCode: countryData[0].dial_code }, { upsert: true, new: true }) .then((data) => console.log(data)) // console.log(id, resp._id) return res.status(200).json({ message: 'Updated successfuly, Refreshing...', error: 0 }) })Esto es de la interfaz
const updateUser = async () => { await axios.put('/update', { fullname, phone, country, img, title, id }) .then((dataFetched) => { updateIsLoading(false) const { status, data } = dataFetched updateData({ data, status }) window.location.href = '/' }) .catch(err => { updateIsLoading(false) const { data, status } = err.response updateData({ data, status }) }) }Por ejemplo, si edito el registro azul o verde, siempre se eliminará el rojo y se cambiará al documento editado, y esa acción creará un nuevo documento.
Creo que deberías usar {} en find
app.put('/update', async (req, res) => { const { fullname, phone, country, img, title, id } = req.body const countryData = getCountryCodeByName(country) await Contact.findOneAndUpdate({id}, { fullname, title, phone, country, img, countryCode: countryData[0].dial_code }, { upsert: true, new: true }) .then((data) => console.log(data)) // console.log(id, resp._id) return res.status(200).json({ message: 'Updated successfuly, Refreshing...', error: 0 }) })Lo descubro. Quería encontrar un documento por una identificación y usé findOneAndUpdate en lugar de findByIdAndUpdate.
Este código ahora funciona bien.
app.put('/update', async (req, res) => { const { fullname, phone, country, img, title, id } = req.body const countryData = getCountryCodeByName(country) await Contact.findByIdAndUpdate(id, { fullname, phone, country, img, title, countryCode: countryData[0].dial_code }, { new: true }) .then((data) => console.log(data)) .catch((err) => console.log(err)) return res.status(200).json({ message: 'Updated successfuly, Refreshing...', error: 0 }) })