0

I'm working on a delivery service where I'm processing 8 orders at the same time concurrently, for each of these orders, I must get a unique consignment number that is saved on the database. But since the operations are concurrent, they are all picking up the same object/consignment number.

const query = new Parse.Query("Consign")
        query.doesNotExist("order")
        query.equalTo("staging", staging)
        query.exists("number")
        query.limit(1)
        await query.find().then(function (result) {
            if (result.length > 0) {
                order.set("consign_no", result[0].get("number"))
                result[0].set("order", order)
            } else {
                //failed
            }
        }).catch((err)=>{
            console.log(err);
        })

How do I make this query in such a way that it picks up unique objects even when ran concurrently?

  • I'm not an expert but maybe you find inspiration on https://stackoverflow.com/questions/32728670/mutex-with-mongodb (that leads you to https://stackoverflow.com/questions/9274777/mongodb-as-a-queue-service ) Good luck! – malarres May 20 '21 at 13:29

1 Answers1

0

Based on an answer given here by someone else:

  • Create a counter collection
  • Insert one document into it with {value:1}
  • Whenever you need a value, use find-and-modify to $inc this document and return the new value

This should work (subject to Is it possible to update the same document on concurrent findAndModify operations in Mongo?) for giving you distinct values, note that in your documents the values may end up not being consecutive if you insert a value which you retrieved later first.

D. SM
  • 13,584
  • 3
  • 12
  • 21