Reputation: 758
I am developing a query of tasks. When a task is requested, I am returning the oldest one with the following code:
Task.find({})
// Filter for those that are not started yet
.where('startDate').equals(null)
// Sort ascending to get the oldest
.sort({ reqDate: 'asc' }).findOne(function (err, task) { ... }
Inside of the final brackets, I set the startDate to the current time. The requests are done by calling a single NodeJS (Express) API running express and communicating with MongoDB by using Mongoose.
This works well with just one person requesting tasks, but I am thinking of a huge scale right now. What if there are multiple people requesting in the same moment, all receiving the same task as they come in in the same timespan of a few milliseconds?
Is there a way to make sure that the startDate
of the document is set in the moment it is found by mongoose?
Upvotes: 0
Views: 174
Reputation: 111278
In Mongo there's db.collection.findAndModify()
and db.collection.findOneAndUpdate()
:
But you are likely to get race conditions anyway. You may be better off implementing your queues with Redis, RabbitMQ, ZeroMQ, ActiveMQ, NSQ etc.
See:
Much more tools are here:
To sum it up, you may be able to work around your current problem with db.collection.findAndModify()
and db.collection.findOneAndUpdate()
but using a proper tool for queues or pub/sub will save you a lot of trouble, especially when you start processing multiple tasks concurrently.
Upvotes: 2