mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

when save docs.DATE is always same time

Open unkownY opened this issue 7 years ago • 5 comments

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)

image

VERSION

  • node - v8.12.0
  • mongo - 3.2.21
  • mongoos - 5.2.17

unkownY avatar Dec 14 '18 10:12 unkownY

  1. You don't need the hook for updating updatedAt because that field updated everytime you do an update-query.
  2. You don't need to set a default for createdAt becasue that value also filles itself on creation.
  3. I don't see the error, the times are mostly different. Look at the last 3 digits before the Z at 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.

mhombach avatar Dec 14 '18 10:12 mhombach

Thank for the tips . They are real users, some of them created today, however the createdAt is too close to believe?

unkownY avatar Dec 14 '18 11:12 unkownY

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.

mhombach avatar Dec 14 '18 11:12 mhombach

THX, trying...

unkownY avatar Dec 14 '18 11:12 unkownY

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 :)

vkarpov15 avatar Dec 14 '18 23:12 vkarpov15