mongoose得不到工作(SchemaType#get(fn))

我正在查看mongoose的API文档,并find了get选项。 但是,它似乎不适合我。

这是带有get选项的Schema:

var PostSchema = new Schema({ content: { type: String, required: true }, date: { type: Date, default: Date.now, get: function (val) { return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear() + " " + (val.getHours() + 1) + ":" + (val.getMinutes() + 1) + ":" + (val.getSeconds() + 1); } } }) 

这是我获取所有文件的地方:

 var Post = App.model('post') exports.fetchAll = function (req, res, next) { Post.find({}).sort({date: 'desc'}).exec(function (err, posts) { if (err) { return next(err) } res.json(posts) }) } 

但结果还是一样的。 在客户端,我收到{{post.date}}的非格式string:

 2015-10-18T07:56:24.606Z 

我无法弄清楚为什么格式化的datestring没有得到返回。

通过向模式添加getters: true选项,可以告诉mongoose在将文档转换为JSON时使用getter。 Mongoose使这个选项,因为你可能会或可能不希望在将文档转换为对象(保留原始date对象)或JSON(格式化datestring)时有不同的逻辑:

 var PostSchema = new Schema({ content: { type: String, required: true }, date: { type: Date, default: Date.now, get: function (val) { return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear() + " " + (val.getHours() + 1) + ":" + (val.getMinutes() + 1) + ":" + (val.getSeconds() + 1); } } }, { toJSON: { getters: true } })