Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js and mongoose schema date.now code not working properly

I have created this schema for user registration:

let userSchema = new mongoose.Schema({
    lname: String,
    fname: String,
    username: String,
    email: String,
    password: String,
    registrationDate: {
        type: Date,
        default: Date.now()
    },
    referedBy: {
        type: String,
        default: ''
    },
    referalEnd: {
        type: Date,
        default: Date.now() + 5*365*24*60*60*1000
    },
    userRefererId: {
        type: String,
        default: uniqid()
    }
});

As you can see, there is a Date.now function and uniqid function in the schema.

Those functions can be used approximately once every 5 minutes, because if I create two users a few seconds apart, it generates the same uniqid and shows the same date.

Image of my MongoDB collection

like image 243
Tomas Jucevičius Avatar asked Jul 26 '18 13:07

Tomas Jucevičius


2 Answers

Remove the () from Date.now() and just call Date.now.

like image 197
atsnam Avatar answered Oct 20 '22 05:10

atsnam


I've run into this before, the schema is generated at deployment / start time and not regenerated on each new creation hence why the time is always the same. Its better to generate the date / time outside the new Model().save() call.

like image 22
Alex Naish Avatar answered Oct 20 '22 06:10

Alex Naish