Quantaliinuxite
Quantaliinuxite

Reputation: 3223

Mongoose with NodeJS: Default value for document's Date only updates on server restart

I have a mongoose Schema declared like so:

var PostSchema = new mongoose.Schema({
    timestamp: {type: Number, default: Date.now()},
});

I defined a route to create posts which works great. The code I use to create a post is as follows:

/* POST Create new post (auth required)*/
router.post('/', auth, function(req, res, next) {
  var post = new Post();
  post.save(function(err, post){
    if(err){ return next(err); }
    res.json(post);
  });
});

However I have noticed that my posts' timestamps don't change with... with time! In fact they dont't change at all. As an example, here are the last three posts:

{
_id: "570aa4c946b52c7656cd8cf5",
__v: 0,
timestamp: 1460313633406
},
{
_id: "570aa4e546b52c7656cd8cf6",
__v: 0,
timestamp: 1460313633406
},
{
_id: "570aa59c46b52c7656cd8cf7",
__v: 0,
timestamp: 1460313633406
}

They were all posted within a 20 minute interval, yet they all have the same timestamp.

Upvotes: 2

Views: 1705

Answers (3)

Joschua Schneider
Joschua Schneider

Reputation: 4093

You can pass functions to a mongoose Model, you're assigning a value at the creation of the model. Use just Date.now instead, it will be called every time you save a entry.

default: Date.now() //returns a value at model creation
default: Date.now   //adds the function to the model, mongoose will run any functions passed when a new entry is created -> that is what you need`\

Upvotes: 5

ZeMoon
ZeMoon

Reputation: 20274

The default value was saved as the date that was instantiated at the time the schema object was created, which happens only when the app is started.

You can use a pre hook for the document. The documentation shows an example similar to the situation you have described.

PostSchema.pre('save', function (next) {
    this.timestamp = Date.now();
    next();
});

Upvotes: 2

matanso
matanso

Reputation: 1292

Date.now() instantiates a date with a value of that moment. It doesn't update if the time changes. Since you want a different value for each document's date, you can't use a default value. Instead, upon creation of each document, set its date to Date.now().

Upvotes: 1

Related Questions