Mongoose 5.x schema.pre()查询中间件不起作用

时间:2018-07-19 03:41:45

标签: javascript node.js mongodb mongoose mongoose-schema

使用Mongoose 5.2.4,我正在努力使Query Middleware schema.pre()挂钩正常工作。我的目标是在保存时更新updatedAt字段。除了我使用findOneAndUpdate而不是update之外,我使用了猫鼬文档中的exact code

schema.pre('findOneAndUpdate', function() {
    console.log('pre findoneandupdate fired')
    this.findOneAndUpdate({}, { $set: { updatedAt: new Date() } });
});

我也尝试了以下方法:

schema.pre('findOneAndUpdate', function() {
    console.log('pre findoneandupdate fired')
    this.update({}, { $set: { updatedAt: new Date() } });
});

正在调用该挂钩,因为日志显示“ pre findoneandupdate fired”。另外,您还会在下面注意到,在我的代码中,我调用了findByIdAndUpdate(),该方法最终在后台调用了findOneAndUpdate()。

但是updatedAt不会更新。有任何想法吗?

完整架构:

var schema = new Schema({
    _id: { type: String, default: uuid },
    _customer: { type: String },
    name: { type: String, required: 'required: name' },
    address: {
        address1: { type: String },
        address2: { type: String },
        city: { type: String, required: 'required: city' },
        state: { type: String, required: 'required: state' },
        postcode: { type: String, required: 'required: postcode' },
        country: { type: String, required: 'required: country' }
    },
},
    { timestamps: { } } ,
    { toJSON: { virtuals: true } }
);

schema.pre('findOneAndUpdate', function() {
    console.log('pre findoneandupdate fired')
    this.findOneAndUpdate({}, { $set: { updatedAt: new Date() } });
  });

处理PUT路由的调用Node.js方法:

exports.update = function (req, res) {

var lContinue = true

try {
    //run security checks
    lContinue = _canSave(req, res)
    lContinue = lContinue && req.params.id == req.body._id;

    // We've passed the security tests, attempt to save the asset
    if (lContinue) {
        var saveModel = new Model(req.body)
        Model.findByIdAndUpdate(req.params.id, saveModel, { new: true }, function (err, model) {
            if (err) {
                console.log(err)
                res.send(err)
                lContinue = false
            }
            if (lContinue) {
                if (model != null)
                    // Success - Updated
                    res.status(200).json(model)
                else
                    // Error -- Unknown error
                    res.status(400).send()
            }
        })
    }
}
catch (e) {
    console.log(e)
    res.status(400).send()
}
}

最后一点,我确实尝试将代码重构为使用model.update()并将整个schema.pre调用调整为基于'update'而不是'findbyidandupdate',但这也行不通。

提前感谢您提供任何解决方案!

0 个答案:

没有答案