【问题标题】:Fire another API call in Lifecycle callbacks - Strapi在生命周期回调中触发另一个 API 调用 - Strapi
【发布时间】:2018-10-05 07:53:41
【问题描述】:

我有两种内容类型:Products 和 TempBaskets

Products 包含一个字段; stock-total 我想根据使用此形状创建或更新的 TempBasket 进行更改:

{ 
 "products":{
   "test-product": {
     "quantity":1,
     "id":"5b945b5b91f2d31698893914",
     "price":123
   }
 },
 "id":"5bb6a2c34f119f72182ec975",
 "totals": {
   "items":1,
   "price":123
 }
}

我想在 TempBaskets 生命周期挂钩中捕获这些数据,然后调用 Products 控制器之一并将测试产品的库存更新 -1。

afterUpdate: async (model, result) => {
    console.log(model);
    console.log(result);
    console.log(model.products); // undefined
    console.log(model.body); // undefined
    console.log(model.data); // clutching at straws - undefined 
}

modelresult 是猫鼬对象。文档似乎建议 model.products 应该包含我需要的数据 - 但它是未定义的。

如何从生命周期方法中的调用访问数据?

然后我可以在生命周期挂钩中使用 Products 中的控制器吗?

最后,(抱歉堆栈溢出大神)这是正确的方法吗?

谢谢!

【问题讨论】:

    标签: mongoose strapi


    【解决方案1】:

    我刚刚遇到了这个问题,我不确定这是否是完美的方法,但这是我解决它的方法。

    // Before updating a value.
    // Fired before an `update` query.
    beforeUpdate: async function(model) {
      // Get _id of project being updated
      let documentId = model._conditions._id;
      // Tack it on to the middleware chain so it can be used in post save hook
      this.documentId = documentId;
    },
    
    // After updating a value.
    // Fired after an `update` query.
    afterUpdate: async function(model, result) {
      // Pull the updated project
      let updatedDocument = await this.findById(this.documentId);
    },
    

    注意 async (model) => {}async function(model){} 的变化。 Mongoose 中间件以链的形式运行,因此您可以将数据从 pre-hook 传递到 post-hook。这感觉就像是在进行额外的数据库调用,但由于 Mongoose 的工作原理,我不确定是否有任何解决方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      • 1970-01-01
      • 2015-05-30
      • 2023-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多