带有空数组而不是未定义的猫鼬初始化数组

Mongoose Init Arrays with empty array instead of undefined

经过一些调试,我想出了这段代码:

var trackSchema = new mongoose.Schema({
  title: String,
  playedAtTimestamps: Array
});

trackSchema.post('init', function(track) {
  track.playedAtTimestamps = track.playedAtTimestamps || [];
});

所以在代码的其他地方,我知道 track.playedAtTimestamps 是一个 Array。但我觉得我的 post-init 回调对我的架构定义来说是多余的。

有没有更好的做法?我们应该以某种方式修改 Mongoose 的行为吗?

谢谢

陷阱:facepalm

我在做

  Track.findOne({})
  .select('title') // Here is the mistake, I was not fetching playedAtTimestamps
  .exec(function(err, track){
    console.log(track);
    track.incCounterSync((new Date()).getTime()); // Here is the error
    track.save(function(err, track){
      console.log(track);
    });
  });