As part our requirements we are being asked to create a property which has a unique value, in the context of the collection. We can’t use the Mongo ID, since the UX team for our product indicates the value needs to be a number only, with a certain defined length.
Accepting theses requirements that we need to work with, can anyone suggest an approach of creating a unique id?
The current approach is to create the product number is as follows:
async createProductCode (): Promise<string> {
let productCode;
let product;
do {
const randomVal = getRandomInt(1000000, 9999999);
productCode = `${randomVal}`;
product = await (Product as any).countDocumentsWithDeleted({ code: productCode });
} while (product && product > 0);
return productCode;
}
The issue is that between the time the product code is created and it is used it may be used by another operation. As a workaround we have ensured that production creation is done synchronously, to avoid this issue.
Can anyone suggest a better way to create a unique field value, that could be done in parallel?