Home > Net >  Update values dynamically in MongoDB
Update values dynamically in MongoDB

Time:02-13

I'm working on an inventory management app, and I need to update inventories according to a value provided by the user. Let's say we have 5 of one item, the user adds 3 on the front-end form, the updated value should be 8. I've been unable to make mongo update the number.

router.put('/show/:id', isLoggedIn, catchAsync(async(req, res)=>{
const {id} = req.params;
const qty = parseInt(req.body.cantidad)
if(qty>0){
    const item = await Inv.findById(id)
    const update = parseInt(req.body.cantidad)   item.cantidad
    const updateInv = await Inv.findOneAndUpdate({ item: {cantidad:{$in: update}}}, {new :true})
    res.redirect(`/inv/show/${item._id}`)
} else {
    req.flash('error', 'Revise la cantidad')
    res.redirect('/inv/show')
}}));

And here's my model:

const InvSchema = new Schema({
nombre: {
    type: String,
    required: true,
    unique: true
},
cantidad: Number
});

CodePudding user response:

You didn't change your update statement right. You shouldn't remove the first argument. As I said {new: true} should be the third input. Anyway I think there is a better solution for what you want to do. As you already find the record with findById, you can use mongo/monoose save command instead of another findOneAndUpdate:

router.put('/show/:id', isLoggedIn, catchAsync(async(req, res)=>{
  const {id} = req.params;
  const qty = parseInt(req.body.cantidad)
  if(qty>0){
    const item = await Inv.findById(id)
    item.cantidad = parseInt(req.body.cantidad)   item.cantidad // Change this line to change item's property directly
    await item.save() // Save the item in database
    //const updateInv = await Inv.findOneAndUpdate({ item: {cantidad:{$in: update}}}, {new :true}) // Remove this line
    res.redirect(`/inv/show/${item._id}`)
  } else {
    req.flash('error', 'Revise la cantidad')
    res.redirect('/inv/show')
  }
}));

I think this is a cleaner approach.

  • Related