Reputation: 1843
I want to check if a record is expired after 30 minutes. I do it like this:
if (orderBlocked.createdAt + (30 * 60 * 1000) > Date.now())
My orderBlocked model looks like this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userBlockedSchema = new Schema({
_id: Schema.Types.ObjectId,
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
attemp: {
type: Number,
required: true
},
createdAt: {
type: Number,
default: Date.now()
},
});
const VerificationClass = mongoose.model('OrderBlocked', userBlockedSchema);
module.exports = VerificationClass;
The orderBlocked.createdAt
field is equal to the time when I restarted the server for the last time. Why does the field has the same value and doesn't update? I console logged both Date.now()
.
console.log(Date.now(), orderBlocked.createdAt);
Immediately after the console.log
ran I looked up the times this is the result:
Date.now()
: (date) 17:41:25 this is the right value
orderBlocked.createdAt
: (date) 15:08:37
Like you can see the orderBlocked.createdAt
is almost 2 hours and 30 minutes less than the Date.now()
, they were both runned on the same moment.
IMPORTANT:
I'm running this application on a nginx
server using ubuntu
.
What am I doing wrong, I can't find any related topics to this problem.
Upvotes: 1
Views: 150
Reputation: 386
When you set default value for created_at
, you used Date.now()
.
That is actually function execution which returns a value, and that value is set as default. As that code executes when you run your app(restart server), that time will be used as default value.
You want to pass function reference as default value (mongoose knows that it should execute it every time to get default value).
Replace this line:
default: Date.now()
with this one:
default: Date.now
Read more about mongoose defaults here: https://mongoosejs.com/docs/defaults.html
Upvotes: 1