J
J
Junior Eternal2018-10-04 23:06:10
JavaScript
Junior Eternal, 2018-10-04 23:06:10

Saving a mongoose model?

Good evening! Help me figure out how to properly save models through mongoose.
Example:
There is a user authorization middleware from which mongoose userModel is thrown into the request
Next, we work with this model as with a regular object, a chain of various asynchronous services is called in the controller and the model is filled with data
At the end of the controller, userModel.save () is called
Returning the answer
Problem:
userModel contains the counter, clicks on the button. Let it be 0 by default.
Several practically simultaneous requests arrive from the front, in parallel we get from the database and create two userModels, each with a counter of 0.
Each one increments userModel.count += 1 and saves the result.
As a result, we get count === 1, due to the fact that at the time of receiving data in the second request, the first one has not yet completed its work and the database is still 0. But the user has performed two actions and it is necessary that there are no such collisions and the counter was equal to 2.
I know about the $inc operator in mongo, but fields can be not only in the form of counters.
How to build a job? Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Shumov, 2018-10-04
@inoise

Queues

P
Pavlo Ponomarenko, 2018-10-05
@TheShock

If this is so important to you, I'm sure you should read about "transactions in mongo". Or even switch to SQL databases, where they are implemented much more comfortably

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question