Sorry, sure this one has been asked a million times before, but i just couldn't find the answer.
What I'm trying to accomplish is to make several different containers to process documents from single mongo collection (processing takes about 20 seconds), and it should be impossible for containers to grab and start processing the same document. Even something short like:
doc = model.findOne({unprocessed: true});
doc.unprocessed = false;
doc.save();
is still not atomic and destined to fail at some point. Is there any way to accomplish this by means of mongo and JS alone, without using queues like redis or rabbitMQ?
CodePudding user response:
You could use findOneAndUpdate which updates a field immediately when a document is retrieved.
doc = await model.findOneAndUpdate({ status: 'unprocessed' }, { status: 'processing' });
// do stuff, then
doc.status = 'processed';
await doc.save();