Arrays Mongoose Init数组为空,而不是未定义
经过一些调试,我得到了以下代码:Arrays Mongoose Init数组为空,而不是未定义,arrays,node.js,mongodb,mongoose,Arrays,Node.js,Mongodb,Mongoose,经过一些调试,我得到了以下代码: var trackSchema = new mongoose.Schema({ title: String, playedAtTimestamps: Array }); trackSchema.post('init', function(track) { track.playedAtTimestamps = track.playedAtTimestamps || []; }); 因此,在代码中的任何其他地方,我都知道track.playedAtT
var trackSchema = new mongoose.Schema({
title: String,
playedAtTimestamps: Array
});
trackSchema.post('init', function(track) {
track.playedAtTimestamps = track.playedAtTimestamps || [];
});
因此,在代码中的任何其他地方,我都知道track.playedAtTimestamps
是一个数组
。但是我感觉我的post-init回调对于我的模式定义来说是多余的
有更好的做法吗?我们应该改变猫鼬的行为吗
谢谢抓到你了: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);
});
});
您不需要post-init中间件,
playedAtTimestamps
默认情况下已经是空数组。您是否看到其他内容?是的,我将track.playedAtTimestamps
设置为undefined
,这会在执行track.playedAtTimestamps.push(newTimestamp)
时引发错误……您能否用代码更新您的问题以重现此问题?当我尝试它时,它起作用了。