mongoose - 在生命周期回调中触发另一个 API 调用 - Strapi
问题描述
我有两种内容类型:产品和 TempBaskets
Products 包含一个字段;stock-total
我想根据使用此形状创建或更新的 TempBaskets 进行更改:
{
"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
}
model
并且result
是猫鼬对象。文档似乎建议model.products
应该包含我需要的数据 - 但它是未定义的。
如何从生命周期方法中的调用访问数据?
然后我可以在生命周期挂钩中使用 Products 中的控制器吗?
最后,(对不起堆栈溢出神)这是正确的方法吗?
谢谢!
解决方案
我刚刚遇到了这个问题,我不确定这是否是完美的方法,但这就是我解决它的方法。
// 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 的工作方式,我不确定是否有任何方法可以解决这个问题。
推荐阅读
- bash - 将此程序简化为一行
- ios - UICollectionView 崩溃
- android - 使用 Dagger 2 对整个应用程序使用 MediaBrowserCompat 的单个实例
- javascript - 如何以角度创建自定义formio复选框组件
- hibernate - com.dao.impl.EnvironmentPropertyRepositoryImpl 中构造函数的参数 0 需要找不到类型为“java.lang.Class”的 bean
- shell - 结合“aws iam list-users”的输出和“aws iam list-groups-for-user”的相应信息
- json - 如何在 typeScript 中访问 JSON 属性
- node.js - NodeJS 无法处理标头 > 8KB 的请求
- sql - SQL - 在一个没有不规则空值的表中联合所有用户
- git - Git fetch 未按预期工作“:gone]”未添加到分支描述中