1
我已经定义了这个模式更新日期字段不更新
var docSchema = mongoose.Schema({
name:{type:String,required:true},
}, { timestamps: { createdAt: 'createdAt',updatedAt:'updatedAt' }, collection : 'docs', discriminatorKey : '_type' });
我更新使用这条路线
router.post('/:id', auth, function(req,res,next) {
var id = req.params.id;
docA.findByIdAndUpdate(id, req.body, {new: true}, function(err, doc) {
if(err)
res.json(err);
else if(doc==null)
res.status(404).send({
message: "Document not found"
});
else
res.json(doc);
});
});
我注意到updatedAt
当我保存了一些编辑的文件不会被更新的文件。 除了这个问题,思考它,它可帮助保持这种数据更新日期阵列状的形式:
updatedAt : [
"2016-10-25T12:52:44.967Z",
"2016-11-10T12:52:44.967Z",
"2016-12-01T12:52:44.967Z"
]
SOLUTION(?):根据@chridam建议,我目前的解决方法不断更新的日期数组是:
docSchema.pre(`findOneAndUpdate`, function(next) {
if(!this._update.updateHistory) {
console.log("findOneAndUpdate hook: updateHistory not present")
this._update.updateHistory=[];
}
this._update.updateHistory.push(new Date);
return next();
});
docSchema.pre('save', function (next) {
if(!this.updateHistory) {
console.log("Save hook: updateHistory not present")
this.updateHistory=[];
}
this.updateHistory.push(new Date);
next();
});
正如你可以看到我使用discriminatorKey,所以我有几个继承模型到'doc':'docA','docB','docC','docD' .. 也许pre保存钩子会提供相同的解决方法?它应该处理创建和编辑,但是..我会避免去多条路线 – alfredopacino
是的,更新前的钩子听起来像是你的理想路线。检查更新的答案。 – chridam
请检查我编辑的问题 – alfredopacino