I've encountered a challenge in my current implementation. I'm utilizing queues to invoke a specific function (let's call it function a()) within a loop. The loop triggers the queue, leading to multiple calls of the same function a().
Inside function a(), I'm generating a number based on the totalCountOfSavedDocs + 1. For instance, if the savedOrders are 10, the next one should logically be 1. The generated number is then stored in the database (using mongodb) for the next doc saving.
However, due to the loop and the multiple queue calls, the number generation is not happening sequentially. Consequently, I'm facing an issue where the same number is being assigned to multiple documents.
I'd appreciate any insights or suggestions on how to ensure the sequential generation of numbers despite the loop and multiple queue calls.
Here is the code : This is how queue is called :
for await (let order of orders) {
const msg: ServiceBusMessage = {
body: JSON.stringify({
type: "order-create-single",
data: order,
req: reqObj,
})
};
await sender.sendMessages(msg);
}
IN queue :
public async process(orderObj: IOrderAddRequest, req: any) {
try {
await this.addOrderService.createOrder(req, orderObj);
}
catch (err) {
throw err;
}
}
sequence numberas a set and get. So you can update the sequential number in the message body and update in database with an increment. Start the sequential number from 1, get the sequential number from the database, and increment it before sending the queue/database. Refer to this doc for auto-incrementing IDs in MongoDB.For creating a Service Bus client and sender for a queue. Refer to below:-
getPreviousNumberFunction:storeNumberInDatabaseAzure: