【问题标题】:mongoose pre hook findOneAndUpdate modify some field getting from another collectionmongoose pre hook findOneAndUpdate 修改从另一个集合中获取的某些字段
【发布时间】:2018-12-28 21:06:50
【问题描述】:

我正在尝试修改 findOneAndUpdate 预挂钩中的文档,代码如下

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

})

我遇到了错误

TypeError: Cannot read property '$set' of undefined

我知道为什么会出现这个错误,因为我正在访问 promise 中的“this”关键字,promise 中的“this”与 pre 方法后的“this”不同 如何解决这个问题,我试图通过分配来解决这个问题 this._update.$set 设置为注释代码中示例中显示的不同值,但保存后不会修改文档,我们只需要更改 this._update.$set.salaray 值。任何帮助表示赞赏

【问题讨论】:

    标签: javascript node.js mongodb mongoose promise


    【解决方案1】:

    您可以使用.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)
    })
    
    })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-19
      • 2021-02-11
      • 1970-01-01
      • 2015-10-27
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 2017-01-01
      相关资源
      最近更新 更多