在猫鼬中抑制施法到日期,用吸气剂变身后

Suppress cast to Date in mongoose, after transforming with getter

本文关键字:身后 变身 日期 施法      更新时间:2023-09-26

我的猫鼬架构中有一个日期字段,我想将其转换为常规日期进行显示。这样做的明显位置是在 getter 中,以避免到处调用 prettifyDate 函数。这是行不通的,因为猫鼬似乎正在获取我的 post-getter 字符串并将其提供给Date构造函数:

...
, date: {type: Date, get: function() { return 'foo'; }} 
...

在我的模式中给我:

Cast to date failed for value "foo"

当我获取文档时。

是否可以将这种强制转换为Date?有没有更好的方法让我错过?

接受的答案是可以的,但我认为您应该为此使用虚拟。它们是专门为这样的事情而制作的。

schema.virtual('formatted_date').get(function () {
  // Code for prettifying where you refer to this.date
  return prettifiedDate;
});

这样,您就不会在架构中放置额外的字段(仅用作虚拟字段)

在当前版本的猫鼬(3.8)中,它工作正常:

date: {type: Date, get: function(v) { return 'foo'; }}   // yields 'foo' without errors

我刚刚在做完全相同的事情,并提出了这个解决方法:

, date: {type: Date}
, formatted_date: {type : String, get : prettifyDate}

然后在 prettifyDate 函数引用中: 这个.日期

这不太可能是最好的方法,但它有效。请记住使用 .toISOString() 转换日期,以便在函数中使用原始 ISO 日期。