There are no items in your cart
Add More
Add More
Item Details | Price |
---|
Sat Dec 31, 2022
In Mongoose, you can increment or decrement a value of a field in a document using promises instead of callbacks by using the $inc
operator and updateOne()
or findByIdAndUpdate()
methods.
To increment a value, you can use the following syntax:
Model.updateOne({ _id: id }, { $inc: { field: value } }) .then(() => { // success }) .catch((err) => { // error });
Where "Model" is the name of your Mongoose model, "id" is the _id of the document you want to update, "field" is the field you want to increment, and "value" is the amount you want to increment by.
For example, if you have a model named "Counter" and you want to increment the "count" field by 1, you would use the following:
Counter.updateOne({ _id: id }, { $inc: { count: 1 } }) .then(() => { // success }) .catch((err) => { // error });
You can use the same syntax with a negative value to decrement a value. For example, if you want to decrement the "count" field by 1, you would use the following:
Counter.updateOne({ _id: id }, { $inc: { count: -1 } }) .then(() => { // success }) .catch((err) => { // error });
Additionally, Mongoose has a built-in findByIdAndUpdate()
method that you can use to increment or decrement a value in a specific document by its _id using promise pattern
Model.findByIdAndUpdate(id, { $inc: { field: value } }, { new: true }) .then((doc) => { // success }) .catch((err) => { // error });
DCT Academy
Full Stack web development training institute in Bangalore