我正在将findOneAndUpdate()
函数与upsert:true
结合使用,以实现“创建或更新”功能。
这可以正常工作,但是我需要一个中间件函数,该函数根据文档中的数据计算一些总计。
如果文档存在,那也可以。
基于猫鼬(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为null,因为尚未找到。我可以访问需要在中间件中添加的文档吗?
这是我的完整代码。
控制器:
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()
}
}
})
答案 0 :(得分:0)
使用this._update设置“ docToUpdate”来解决此问题。
钩子函数中的代码现在看起来像这样,并且可以正常工作!
let docToUpdate = await this.model.findOne(this.getQuery())
if (!docToUpdate) {
// console.log('no doc found', this)
// return next()
docToUpdate = this._update
}