如何在Pre Update Mongoose中间软件中访问文档对象



考虑一下,我有一个像这样的猫态模式

const mySchema = new mongoose.schema({
val1:Number,
val2:Number
val_1_isBigger:Boolean})

现在我想比较val1&Val2在每次更新之前,我想设置val_1_isbigger的布尔属性。

我的问题是如何在Pre('Update'(Mongoose插件操作中访问文档对象。查看以下示例

mySChema.plugin(function(schema, options) {
    schema.pre('update', function(next) {
//Here How Do I compare val1 & val2 before update happens
//and then set value here accordingly
  this.update({}, { $set: { val_1_isBigger: true/false } });
}
}

我所做的就是使用_conditions参数获取具有查询ID的文档。使用该文档,您可以执行必要的操作,然后将新对象设置为使用_update更新。我的代码看起来像这样:

userSchema.pre('update', function(next) {
    if (this._conditions) {
        _id = this._conditions.id || '';
        User.findOne({ id : _id }).exec().then((user) => {
            if (user.token === undefined) {
                this._update['$set'].token = 'some token';
                next();
            }
        }); 
    }
    next();
});

我希望它有帮助。

最新更新