【问题标题】:Updated date field is not updated更新日期字段未更新
【发布时间】:2016-12-01 12:18:43
【问题描述】:

我已经定义了这个架构

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

【问题讨论】:

    标签: mongodb express mongoose


    【解决方案1】:

    这是一个已知问题,请参考插件here的原帖,其中dunnkerscommented

    实际上不可能将中间件挂接到更新上, findByIdAndUpdatefindOneAndUpdatefindOneAndRemovefindByIdAndRemove 目前在 Mongoose。

    这意味着在使用其中任何一个时实际上都没有运行任何插件 功能。

    查看 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,所以我有几个继承模型到docdocA,docB,docC,docD.. 也许是一个预保存钩子会提供相同的解决方法吗?但是它应该处理创建和编辑.. 我会避免修补大量路线
    • 是的,更新前挂钩听起来是您的理想选择。检查更新的答案。
    • 检查this._update.updateHistory 看起来可行,但我不完全确定检查是否正确
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 2021-06-23
    • 1970-01-01
    • 2018-02-09
    • 2017-11-15
    • 1970-01-01
    相关资源
    最近更新 更多