Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js mongoose中间件获取将添加的文档_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js mongoose中间件获取将添加的文档

Node.js mongoose中间件获取将添加的文档,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我将findOneAndUpdate()函数与upsert:true一起用于“创建或更新”函数。 这很好,但我需要一个中间件函数,它根据文档中的数据计算一些总数。 如果文档存在,也可以这样做。 根据mongoose()文档中的注释,我得到了包含以下代码的文档: schema.pre('findOneAndUpdate', async function (next) { const docToUpdate = await this.model.findOne(this.getQuery())

我将
findOneAndUpdate()
函数与
upsert:true
一起用于“创建或更新”函数。 这很好,但我需要一个中间件函数,它根据文档中的数据计算一些总数。 如果文档存在,也可以这样做。 根据mongoose()文档中的注释,我得到了包含以下代码的文档:

schema.pre('findOneAndUpdate', async function (next) {
  const docToUpdate = await this.model.findOne(this.getQuery())
})
然后我循环查看
docToUpdate.details
以汇总一些金额,并使用
this进行设置。\u 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()
    }
  }
})
transaction.pre('findOneAndUpdate',异步函数(下一个){
//计算详细信息的所有总计,并使用此更新TransactionTotal。
const docToUpdate=等待this.model.findOne(this.getQuery())
如果(!docToUpdate){
//当文档被升级时,代码将达到此值
console.log('未找到文档',此)
返回下一个()
}
让transactionTotal=0
设计数器=0
for(设i=0;i
通过使用此更新设置“docToUpdate”解决了此问题

to hook函数中的代码现在看起来是这样的,并且正在工作

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

请在jsoneditor online上共享收藏和您想要的内容