Dev
Dev

Reputation: 423

mongoose pre hook findOneAndUpdate modify some field getting from another collection

I'm trying to modify a document in findOneAndUpdate pre hook, code given below

userSchema.pre('findOneAndUpdate', function (next) {
// this._update.$set
//var user = new User(this._update.$set)

var promiseArray = []  
promiseArray.push(// Fetching some data from other collection)

Promise.all(promiseArray).then(function (values) {

if (values[0].length === 0) {

  return next('Data not found')
} else {                    
    this._update.$set.salary = values.salary          
    return next()
}
}).catch(function (err) {    
next(err)
})

})

I'm getting error

TypeError: Cannot read property '$set' of undefined

I know why i'm getting this error because i'm accessing "this" keyword inside promise, "this" inside promise is different than "this" after pre method How to solve this problem, I have tried to solve this problem by assigning this._update.$set to different value shown example in commented code but after saving it's not modifying document we need to only change this._update.$set.salaray value. Any help appreciated

Upvotes: 0

Views: 727

Answers (1)

Mr.Js
Mr.Js

Reputation: 96

You can use .bind()

Promise.all(promiseArray).then(function (values) {

if (values[0].length === 0) {

  return next('Data not found')
} else {                    
    this._update.$set.salary = values.salary          
    return next()
}
}.bind(this)).catch(function (err) {    
next(err)
})

})

Upvotes: 1

Related Questions