I made a user schema based on mongoose or mongodb, in which there is a invitation code and this code is always unique in the database.
import randomize from 'randomatic';
const userSchema = new Schema<UserDataInterface>(
{
username: {
type: String,
required: [true, "Please username is mandatory."],
unique: false,
},
inviteCode: { type: String, default: randomize('0', 8) },
...
}
The invite code is 8 length long numbers generated by a randomatic library, I expect it will be different for every user, so I didn't enforce inviteCode to be unique
but during the production, I found two latest registered users who are registered at different time have exact the same invitecode.
{
"_id": {
"$oid": "6656e341495d3ec1782baa7d"
},
"username": "ddd333",
"inviteCode": "94770150",
"createdAt": {
"$date": "2024-05-29T08:11:45.240Z"
}
}
{
"_id": {
"$oid": "66572d68495d3ec1782bab0f"
},
"username": "ddd233",
"inviteCode": "94770150",
"createdAt": {
"$date": "2024-05-29T13:28:08.943Z"
}
}
I found the problem is all user's inviteCode is the same value,
inviteCode: { type: String, default: randomize('0', 8) }.
It looks like randomize function only initalize only once
randomize()when the schema is defined instead of passing the function. That means when the script runs the default value will be the return value of the function invocation and therefore will always be the same as it's only called once. Pass a function instead.