【发布时间】: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分享收藏和你想要的东西