Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

308
Vistas
Mongoose findOneAndUpdate() creates a new object

I'm trying via PUT request to backend to update an existing document by using findOneAndUpdate(). the result of my code is that a replica of the original document is created rather updating the exisiting one and first record on page is removed.

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
    })
})

This is from frontend

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 })
            })
    }

For example if I edit either the blue or green record, always the red one will be removed and changed to the edited document, and a new document will be created by that action.

Example for code behaviour

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I think you shoud use {} in 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
        })
    })
about 4 years ago · Juan Pablo Isaza Denunciar

0

I figure it out. I wanted to find a document by an id and used findOneAndUpdate rather than findByIdAndUpdate.

This code now works just fine.

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
    })
})

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda