【问题标题】:mongoose middleware get document which will be added猫鼬中间件获取将被添加的文档
【发布时间】:2020-04-15 12:45:57
【问题描述】:

我将findOneAndUpdate() 函数与upsert:true 一起用于“创建或更新”函数。 这很好用,但我想要一个中间件函数,它根据文档中的数据计算一些总数。 如果文档存在,这也可以正常工作。 根据 mongoose (https://mongoosejs.com/docs/middleware.html#notes) 文档中的注释,我得到了包含以下代码的文档:

schema.pre('findOneAndUpdate', async function (next) {
  const docToUpdate = await this.model.findOne(this.getQuery())
})

然后我循环遍历 docToUpdate.details 以总结一些金额并将其设置为 this._update.total = totalSum

但是当添加一个新文档时,docToUpdate 为空,因为它还没有找到。能否访问需要添加到中间件的文档,如何访问?

这是我的完整代码。

控制器:

const transaction = req.body.transaction
if (!transaction._id) transaction._id = new ObjectId()

// Use the findOneAndModify function with upsert to create or update the transaction
Transaction.findOneAndUpdate({ _id: transaction._id }, transaction, { upsert: true, setDefaultsOnInsert: true }, function (err, result) {
  if (err) {
    return res.status(500).json({ message: err })
  }
  return res.status(200).json({ message: 'OK', result })
})

型号:

transaction.pre('findOneAndUpdate', async function (next) {
  // count all totals for the details and update the TransactionTotal with this.
  const docToUpdate = await this.model.findOne(this.getQuery())
  if (!docToUpdate) {
    // code will reach this when the document is being upserted
    console.log('no doc found', this)
    return next()
  }
  let transactionTotal = 0
  let counter = 0

  for (let i = 0; i < docToUpdate.details.length; i++) {
    transactionTotal += docToUpdate.details[i].total
    counter++
    if (counter === docToUpdate.details.length) {
      this._update.transactionTotal = transactionTotal
      next()
    }
  }
})

【问题讨论】:

  • 请在线jsoneditor分享收藏和你想要的东西

标签: node.js mongodb mongoose


【解决方案1】:

通过使用 this._update 设置 'docToUpdate' 解决了这个问题。

钩子函数中的代码现在看起来像这样,并且可以正常工作!

let docToUpdate = await this.model.findOne(this.getQuery())
if (!docToUpdate) {
  // console.log('no doc found', this)
  // return next()
  docToUpdate = this._update
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-10
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2019-10-06
    • 2017-11-24
    • 2016-07-30
    相关资源
    最近更新 更多