Creating random unique field value, via NodeJS?

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?

Hi @Andre-John_Mas,

Welcome to MongoDB Community.

I found a creative way to do it using pipeline updates and $rand aggregation. Those updateOne are atomic.

I am using “Upsert” with a new _id to mimic an “insert” operation if needed:

db.randomSamples.updateOne(
   {_id : ObjectId()},
   [{$set: {
  productCode: {
    $trunc : [ {$multiply: [
      {
        $rand: {}
      },
      100000000000000
    ]
  }, -1]
}
}}], {upsert : true}
)

This creates random productCodes:

{ _id: ObjectID("60226a260439653f31ecd23a"),
  productCode: 57465943495130 }
{ _id: ObjectID("60226a490439653f31ecd23b"),
  productCode: 87144984542740 }

Thanks,
Pavel