简体   繁体   中英

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

You can try the following for object merging

Object.assign(product, req.body)

note : i haven't tried with mongoose collection

You can use updateMany or findOneAndUpdate model methods, but it is more advisable to use .save()

https://mongoosejs.com/docs/api.html#model_Model.updateMany

https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate

If you want to .save() to look cleaner, you can do like this:

async updateEntity(payload) {
     const keysToUpdate = Object.keys(payload)
     if (keysToUpdate.length === 0) {
         throw new Error('Update payload must not be empty!')
     }
    const entity = await entityModel.findOne({ _id: redirect })
    keysToUpdate.forEach((key) => {
       entity[key] = payload[key]
    })
await entity.save()}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM