when save docs.DATE is always same time
Quesion
when user join in ,i save their ID(uid) ,join time( createdAt )
the Q is:createdAt is same time
it's impossible, user count below 300
should I change code ,or I use it in a wrong way ?
THX.
code
let _PlantUser = new Schema({
uid:{type:String,required:true,unique:true},
createdAt:{type:Date,default:Date.now()},
updatedAt:Date,
});
_PlantUser.pre('save',function(next){
this.updatedAt = new Date();
next();
});
mongo result (createdAt)

VERSION
- node - v8.12.0
- mongo - 3.2.21
- mongoos - 5.2.17
- You don't need the hook for updating
updatedAtbecause that field updated everytime you do an update-query. - You don't need to set a default for
createdAtbecasue that value also filles itself on creation. - I don't see the error, the times are mostly different. Look at the last 3 digits before the
Zat the end, these are microseconds. These entries are showing that the top 7 entries were created within 1 second. If that is not meant to be correct, then you need to tell us, when and how these entries are created :)
My guess is, that you are creating dummy-users and you are creating multiple with one "call" sometimes. might be wrong, but then tell us abotu the process of creation.
Thank for the tips .
They are real users, some of them created today,
however the createdAt is too close to believe?
If those are really real users, then do a console.log(JSON.stringify(this)); inside the pre-save hook and analyse what's going on there. Maybe you have a buf somewhere that creates between 1 and 10 users per registration or some other weird behaviour...
edit: also try to reproduce this, when you ahve the loggin inside the hook, by registering some fake users yourself.
THX, trying...
Do this instead:
let _PlantUser = new Schema({
uid:{type:String,required:true,unique:true},
createdAt:{type:Date,default:() => Date.now()},
updatedAt:Date,
});
You really want default to be a function. The behavior you're seeing is because Date.now() is a primitive, so it is equivalent to doing createdAt:{type:Date,default:1544829069157}. Not very useful.
Mongoose also has built-in timestamps that you can use so you can save yourself the headache of implementing them yourself :)