更新日期字段不更新
问题描述:
我已经定义了这个模式更新日期字段不更新
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();
});
答
这是一个已知的问题,请参考原文线程插件here,其中dunnkerscommented:
它实际上是不可能的钩中间件到更新,此刻
findByIdAndUpdate
,findOneAndUpdate
,在猫鼬findOneAndRemove
和findByIdAndRemove
。这意味着在使用这些 函数中的任何一个函数时都不会实际运行插件。
请查阅 中间件的Mongoose文档中的notes部分。问题Automattic/mongoose#964也描述了这一点。
作为一个建议的解决方法,保理模式中的变化:
var docSchema = mongoose.Schema({
"name": { "type": String, "required": true },
"updateHistory": [Date]
}, {
"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 {
doc.updateHistory.push(new Date());
doc.save().then(function(doc){
res.json(doc);
}, function(err) {
// want to handle errors here
})
}
});
});
另一种方法是将一个钩连接到架构:
docSchema.pre("findOneAndUpdate", function() {
this.updatedAt = Date.now();
});
正如你可以看到我使用discriminatorKey,所以我有几个继承模型到'doc':'docA','docB','docC','docD' .. 也许pre保存钩子会提供相同的解决方法?它应该处理创建和编辑,但是..我会避免去多条路线 – alfredopacino
是的,更新前的钩子听起来像是你的理想路线。检查更新的答案。 – chridam
请检查我编辑的问题 – alfredopacino