How can I access the document object in mongoose pre-update staging tool?

believe that I have such a mongoose scheme

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

      

Now I want to compare both val1 and val2 before every update, and accordingly, I want to set the Boolean attribute for val_1_isBigger.

My question is, how can I access the document object during the pre ('update') mongoose plugin operation. Take a look at the following example

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

}
}

      

+3


source to share


1 answer


What I did was use the _conditions parameter to get the document with the request id. With the help of the document, you can perform the necessary operations and then set the new object to update using _update. My code looks like this:

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

      



Hope this helps.

0


source







All Articles