uuid repeated many times
frani opened this issue · 2 comments
Describe the bug
I generate a UUID to set on every object that persist in a MongoDB, after two month of develop we realise that we have many UUID repeated:
- 7 % with => 26130a26-8a17-4338-8b07-54516d3dc1a8
- 5 % with => d56f1da2-f1f5-4ecc-96f2-ff2725c05c7f
- 5 % with => 7d28aa23-3b21-4ee1-a1cb-b34b0e7a7299
- 4 % with => d4440d2b-fc2a-4ccd-a9da-f8d3490a4b6b
- 3 % with => 3bd1baf0-168d-49d8-9c0f-62a4de1877f1
...
and so on.
[Clear, concise description of the problem]
How to reproduce
and example of my model schema and how I am calling UUID:
const mongoose = require('mongoose')
const { v4: uuid } = require('uuid')
const model = new mongoose.Schema(
{
uuid: {
type: String,
default: uuid(),
unique: true,
required: true,
index: true
},
...
},
{
collection: vars.mongo.collections.model,
}
)
Expected behavior
generate different UUIDs every time that I created a new object to persist in my DB
Runtime
- OS: Linux
- Runtime: Node.js
- Runtime Version: v12.18.3
You're specifying a fixed uuid string for your uuid
column's default value (uuid()
is evaluated immediately, so whatever uuid that returns is your default value). Any/all models created w/out an explicit uuid
property will all have that [duplicate] uuid. The reason you're getting duplicates on a variety of uuids is that the default uuid changes each time the process restarts.
I suspect what you want is to pass uuid
as the default function by doing default: uuid,
instead of default: uuid(),
.
Side note: With both unique
and index
enabled I'm surprised Mongo didn't throw when you attempted to insert duplicates. (Not a Mongo user, but I assume unique indexes behave similarly to MySQL et al.)
Figuring out how to fix up that DB is gonna be a challenge...
thanks for this nice explain,
your suspects were right!
and about mongoose, may be I was wrong of how I declared model
I found a note that recomend to declare index in the next way:
const mongoose = require('mongoose')
const { v4: uuidv4 } = require('uuid')
const model = new mongoose.Schema(
{
uuid: {
type: String,
default: uuidv4,
required: true
},
...
},
{
collection: vars.mongo.collections.model,
}
)
model.index(
{
uuid: 1
},
{
unique: true
}
)
thanks for fast responde, answer and the gif haha