带有nodejs和mongoose的时间戳

我正在学习nodeJS,所以我做了这个教程( http://scotch.io/tutorials/javascript/creating-a-single-page-todo-app-with-node-and-angular ),现在我想添加时间戳与每个待办事项。

我用moment.js创build一个简单的文件(time.js)

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

并将其连接到我的路线文件

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

在这里,我得到我的服务器启动时间,而不是我POST的时间(多数民众赞成我需要)

这里出来了

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

如何获得每个请求的当前时间?

有mongoose架构公开为你处理默认值的函数。 这些默认值可以是计算的。 在这个例子中,实现你在这里要求的正确和简单的方法如下

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

当你保存的对象,你不需要指定“date”字段了,mongoose会照顾它!

Mongoose Docs: http : //mongoosejs.com/docs/2.7.x/docs/defaults.html (旧) http://mongoosejs.com/docs/schematypes.html (当前版本)

为什么要经过所有额外的工作,而不是将模式中的时间字段定义为Datetypes,并使用中间件进行设置?

 var todoSchema = mongoose.Schema({ time: Date }); todoSchema.pre('save', function (next) { if (!this.isNew) next(); this.time = new Date(); next(); });