Mongodb 更新日期字段未更新

Mongodb 更新日期字段未更新,mongodb,express,mongoose,Mongodb,Express,Mongoose,我已经定义了这个模式 var docSchema = mongoose.Schema({ name:{type:String,required:true}, }, { timestamps: { createdAt: 'createdAt',updatedAt:'updatedAt' }, collection : 'docs', discriminatorKey : '_type' }); 我使用此路径更新文档 router.post('/:id', auth, function(r

我已经定义了这个模式

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"
]
解决方案(?):根据@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();
});

这是一个已知问题,请参考插件上的原始线程,其中:

实际上不可能将中间件挂接到更新上,
findbyiandupdate
findOneAndUpdate
findOneAndRemove
目前在猫鼬中查找并删除

这意味着在使用这些插件时,实际上没有运行任何插件 功能

查看Mongoose文档中的部分了解更多信息 中间件。本期还对此进行了描述

作为建议的解决方法,将架构更改考虑在内:

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();
});

正如您所看到的,我使用了一个鉴别器键,因此我有几个继承的模型来
doc
docA
docB
docC
docD
。。也许预保存挂钩也能提供同样的解决方法?但是,它应该处理创建和编辑。。我会避免塞满成吨的路线是的,一个更新前的钩子听起来是你的理想路线。检查更新的答案。检查
这个。_update.updateHistory
它看起来可以工作,但我不完全确定检查是否正确