Skip to content
Advertisement

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]?

Advertisement

Answer

You can try the following for object merging

Object.assign(product, req.body)

note: i haven’t tried with mongoose collection

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement