Search code examples
node.jsmongodbmongooseuuid

Nodejs UUIDv4 producing constant id value when used in Mongoose


Recently I noticed that my UUIDv4 generator is having a high rate of collision. I use it to generate UUIDs for my mongodb objects like this:

const mongoose = require('mongoose');
const uuid = require('uuid/v4');

const { Schema } = mongoose;

const ObjectSchema = new Schema({
  UUID: { type: String, required: true, default: uuid() },
  ...})

Expected Output

[
  {
    UUID: '079f67e1-4532-49fc-b7e6-2e6970c8702f',
    _id: 5e0aa675f900cb561bf51fac,

  },
  {
    UUID: 'afbc0fd4-99aa-4d73-88d7-a4724fb3df30',
    _id: 5e0aa675f900cb561bf51fad,

  },
  {
    UUID: '39b099b5-9eaf-4ac3-8d4b-1380369090b5',
    _id: 5e0aa675f900cb561bf51fae,

  }
]

Actual Result

 [
      {
        UUID: '39b099b5-9eaf-4ac3-8d4b-1380369090b5',
        _id: 5e0aa675f900cb561bf51fac,

      },
      {
        UUID: '39b099b5-9eaf-4ac3-8d4b-1380369090b5',
        _id: 5e0aa675f900cb561bf51fad,

      },
      {
        UUID: '39b099b5-9eaf-4ac3-8d4b-1380369090b5',
        _id: 5e0aa675f900cb561bf51fae,

      }
    ]

What I noticed recently is that it gives a constant value more often than not. Usually, a new value is assigned when I restart the server. Anyone else having this issue?


Solution

  • The problem with your code is UUID will be generated one time, and it will use that same default value.

    You need to use function form of default like this to generate a different uuid every time:

    UUID: { type: String, required: true, default: () => uuid() }