inc a value mongoose

How to increase a value in Mongoose?

If you are working with Mongoose and want to increase a value in the database, you can use the mongoose.Model.updateOne() method.

Step 1: Find the document

First, you need to find the document that you want to update. You can use the mongoose.Model.findOne() method to find the document based on some criteria.

// Find the document by ID
const doc = await Model.findOne({ _id: 'some-id' });

Step 2: Update the document

Next, you can use the updateOne() method to update the document. The first argument is the criteria to find the document, and the second argument is the update operation.

To increase a value, you can use the $inc operator. This operator takes an object with keys that represent the fields you want to increment and values that represent the amount to increment by.

// Increase the value of 'count' by 1
const update = { $inc: { count: 1 } };
const result = await Model.updateOne({ _id: 'some-id' }, update);
console.log(result);
// { n: 1, nModified: 1, ok: 1 }

The updateOne() method returns a promise that resolves with an object containing information about the update operation. In this case, it should show that one document was updated and modified.

Alternate approach using findByIdAndUpdate

An alternate approach to do the same is using findByIdAndUpdate() method.

// Increase the value of 'count' by 1
const result = await Model.findByIdAndUpdate('some-id', { $inc: { count: 1 } });
console.log(result);
// { _id: 'some-id', count: 2, ... }

The findByIdAndUpdate() method returns the updated document instead of update operation information.

Conclusion

In this blog post, we looked at how to increase a value in Mongoose using the mongoose.Model.updateOne() method. We also looked at an alternate approach using findByIdAndUpdate() method. These methods can be used in combination with other Mongoose query methods to create powerful and flexible database interactions.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe