我有两种内容类型: Products和TempBaskets
Products包含一个字段;stock-total,我想根据正在创建或更新的TempBaskets来更改它:
{
"products":{
"test-product": {
"quantity":1,
"id":"5b945b5b91f2d31698893914",
"price":123
}
},
"id":"5bb6a2c34f119f72182ec975",
"totals": {
"items":1,
"price":123
}
}我想在TempBaskets生命周期钩子中捕获这些数据,然后调用一个产品控制器并按-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是mongoose对象。文档似乎建议model.products应该包含我需要的数据-但它是未定义的。
如何从生命周期方法中的调用中访问数据?
然后,我可以在生命周期挂钩中使用来自产品的控制器吗?
最后,(对不起,堆栈溢出之神)这是正确的方法吗?
谢谢!
发布于 2018-11-15 21:51:53
我刚刚遇到了这个问题,我不确定这是否是完美的方法,但以下是我如何解决它的。
// 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中间件以链的形式运行,因此您可以将数据从前挂钩传递到后挂钩。这感觉像是在进行额外的数据库调用,但由于Mongoose的工作方式,我不确定是否有任何方法可以绕过这一点。
https://stackoverflow.com/questions/52660846
复制相似问题