Guide to Increasing and Decreasing Field Values using Mongoose

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

Launch your GraphyLaunch your Graphy
100K+ creators trust Graphy to teach online
𝕏
Best MERN Full Stack Development Course | Bangalore | Offline | Online | 100% Placements | Training Institute | Front End Course | React JS Training | Online Course India 2024 Privacy policy Terms of use Contact us Refund policy