Question

I am learning nodeJS now, so I did this tutorial( http://scotch.io/tutorials/javascript/creating-a-single-page-todo-app-with-node-and-angular) , and now I want add timestamp with each todo.

I create a simple file(time.js) with moment.js

var moment = require('moment');
moment().format();
var mytime = moment().format('MMMM Do YYYY, h:mm:ss a');

module.exports = {
time : mytime
}

And connect it to my routes file

var qtime = require('./time');
app.post('/api/todos', function(req, res) {
...
Todo.create({
....
time : qtime.time}
....

Here I get my server startup time, not the time when I POST(thats what I need)

Here the out

"time": "February 21st 2014, 12:00:40 pm",
"time": "February 21st 2014, 12:00:40 pm",
"time": "February 21st 2014, 12:00:40 pm",
...

How to get current time on each request?

Était-ce utile?

La solution

There is function that mongoose schema exposes for you that handles default values. These default values can be calculated ones. In this example, the right and easy way to achieve what you ask here is as follows

new Schema({
    date: { type: Date, default: Date.now }
})

When you save the object, you do not need to specify the "date" field anymore, mongoose will take care of it!

Mongoose Docs: http://mongoosejs.com/docs/2.7.x/docs/defaults.html (old) http://mongoosejs.com/docs/schematypes.html (current version)

Autres conseils

Why go through all that extra work instead of defining your time field in your schema to be of type Date and use middleware to set?

var todoSchema = mongoose.Schema({
  time: Date
});

todoSchema.pre('save', function (next) {
  if (!this.isNew) next();
  this.time = new Date();
  next();
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top