1

I want to update price field to 0.5 * price using mongoose.

what i tried (and works) is finding items, changing them and saving them. but is there any more efficient(better performance) way?

Products.find({} ,
  (err, ps) => {
    ps.forEach(p => {
      p.Price = p.Price * 0.5;
      p.save((err, res) => console.log(err, res))
    });
  }
)

Note that i know how to do this in mongodb (link), but i don't know how to do this in mongoose.

yaya
  • 7,675
  • 1
  • 39
  • 38

1 Answers1

1

You can use $mul for update document.

Products.update({}, { $mul: { price: 0.5} }, { multi: true })

You need to use multi for multiple products.

If you think to use this $set or link

const products = await Products.find({})
const promiseAll = products.map(async (product) => {
   await Products.findOneAndUpdate(
       { _id: product._id } ,
       { $set: { price: product.price * 0.5 }} 
   );
})
await Promise.all(promiseAll)

Or use your promise resolve syntax

Ashok
  • 2,846
  • 1
  • 12
  • 20
  • thanks, what if i wanted to use something like: `price = price - discount` (i mean, subtract or add another column value to it?) – yaya Sep 07 '19 at 13:38
  • { $set: { price: product.price * 0.5 }} it this line do whatever arthmetic you want to do. – Ashok Sep 07 '19 at 13:40
  • isn't this performance as slow as the solustion i mentioned in post (because it runs multiple queries) ? – yaya Sep 07 '19 at 13:43
  • Performance for yours and this solution is nearly the same. And it is standard of code. No problem with multiple queries and document. – Ashok Sep 07 '19 at 13:44
  • thanks. i used mysql for years, but new to nosql(like mongo). consider we have 2k products, a query like this was considered `terrible` in mysql. is there any reason that you're saying `No problem with multiple queries`? doesn't running 2k queries consider bad in mongo? – yaya Sep 07 '19 at 13:59
  • No matter what. I used this type of query once with 18k record to update. – Ashok Sep 07 '19 at 14:02