在用getter变换之后,禁止在mongoose身上施放date
我在我的Mongoose模式中有一个Date字段,我想将其转换为传统的date显示。 明显的地方是在getter中,避免在所有地方调用prettifyDate
函数。 这不起作用,因为似乎mongoose正在采取我的post-getterstring,并将其提供给Date
构造函数:
... , date: {type: Date, get: function() { return 'foo'; }} ...
在我的模式给我:
Cast to date failed for value "foo"
当我拿到一个文件。
是否有可能压制这个铸造Date
? 有没有更好的办法,我失踪了?
我刚刚一直在做同样的事情,并已经想出了这个工作:
, date: {type: Date} , formatted_date: {type : String, get : prettifyDate}
然后在prettifyDate函数中引用:this.date
这不太可能是这样做的最好方法,但它的工作原理。 请记住使用.toISOString()转换date以在您的函数中使用原始ISOdate。
接受的答案是好的,但我认为你应该使用虚拟的。 他们是为了这样的事情而特别制作的。
schema.virtual('formatted_date').get(function () { // Code for prettifying where you refer to this.date return prettifiedDate; });
这样你就不会在你的模式中添加一个额外的字段(它只能用作虚拟)
在当前版本的Mongoose(3.8)中,它工作正常:
date: {type: Date, get: function(v) { return 'foo'; }} // yields 'foo' without errors