Skip to content

is there a way to automatically update everything in a mongoose document?

For example I want to update a mongoose document in a put request, I have to do this:

app.put('/update', async(req,res) => {
  try{
    const product = await Product.findById(req.body.id)
    product.name = req.body.name
    product.price = req.body.price
    procut.discount = req.body.discount
    // etc...
    await product.save()
    res.json(product)
  }catch(e){
    res.json({message: "Error updating the product"})
  }

})

I’m asking if there is another faster and developer friendly way of updating products instead of typing each of the document properties and equal them to the req.body.[property]?

Answer

You can try the following for object merging

Object.assign(product, req.body)

note: i haven’t tried with mongoose collection