Tomas Jucevičius
Tomas Jucevičius

Reputation: 75

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

Upvotes: 6

Views: 2685

Answers (3)

atsnam
atsnam

Reputation: 379

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

Upvotes: 12

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

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

Upvotes: 0

Alex Naish
Alex Naish

Reputation: 120

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.

Upvotes: 4

Related Questions