Node.js: Mongoose default margin markers are not random
I have UserSchema
one like this and I cannot create a unique random one activation_token
.
I am using rand-token
to generate. Found here .
var UserSchema = new Schema({
activation_token: {
type: String,
default: randToken.generate(64),
},
email: {
type: String,
unique: true,
sparse: true
},
first_name: {
type: String
},
last_name: {
type: String
}
});
It seemed to work fine, but when running unit tests with Mocha, all the fields activation_token
were the same. I originally thought it was time related, as this is probably what is used to generate tokens. It is possible that for each new document the timestamp was the same, so I ran some tests with a function that generated about 30 tokens one after the other and they were not alike.
Any ideas on what's going on here?
Here are some examples of the problem:
{
"_id": {
"$oid": "555dfd137c914edc1b41bbda"
},
"email": "oka@haek.io",
"first_name": "Lenora",
"last_name": "Aguilar",
"date_added": {
"$date": "2015-05-21T15:43:01.576Z"
},
"activation_token": "EyBNwu4vxOIXMzj7W5kVOeICfWwxfjXmHkz7ZPHLjkf0MU86QM2aIKNDyvI2YmTR",
"__v": 0
},
{
"_id": {
"$oid": "555dfd107c914edc1b41bbd6"
},
"email": "ediuki@mu.edu",
"first_name": "Eugene",
"last_name": "Green",
"date_added": {
"$date": "2015-05-21T15:43:01.576Z"
},
"activation_token": "EyBNwu4vxOIXMzj7W5kVOeICfWwxfjXmHkz7ZPHLjkf0MU86QM2aIKNDyvI2YmTR",
"__v": 0
}
source to share
It makes sense that they will all be the same. You call generate
once during the schema definition, and you feed the result of that call to the mongoose schema definition, not the function itself. You can try something like this:
var UserSchema = new Schema({
activation_token: {
type: String,
default: function() {
return randToken.generate(64);
}
},
email: {
type: String,
unique: true,
sparse: true
},
first_name: {
type: String
},
last_name: {
type: String
}
});
source to share