'Mongoose unique NanoID

const user = new mongoose.Schema(
  {
    nano_id: {
      type: String,
      required: true,
      default: () => nanoid(7),
      index: { unique: true },
    },
...
}

How to run again nanoid(7) if is not unique? (run automatically and not get any error in console)



Solution 1:[1]

The database will throw an error you have to catch and react to by generating the same record again with a newly generated nanoid.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cachius