node.js - Loopback:为模型实例创建动态属性
问题描述
例如,我有一个回送模型名称Event
,它有 2 个属性,如下所示:
...
"properties": {
"name": {
"type": "string",
"required": true
},
"end": {
"type": "date",
"required": false
}
}...
如何status
使用如下逻辑添加动态属性名称:
if (now() > this.end) {
this.status = 'end';
} else {
this.status = 'running';
}
我也想status
在那些 JSON 响应中包含 Loopback REST API。多谢你们。
解决方案
如果ctx
在远程挂钩或操作挂钩中添加所需的属性,该属性将被添加到模型中并保存到数据库中。
使用远程挂钩,
Event.beforeRemote('*', (ctx, modelInstance, next) => {
ctx.req.body.propertyName = propertyValue;
...
next();
});
在这里,* 可以是任何端点的任何动作。有关更多详细信息,请参阅此。
使用操作挂钩,
Event.observe('before save', (ctx, next) => {
//for insert, full update
if(ctx.instance) {
ctx.instance.propertyName = propertyValue;
...
return next();
}
// for partial update
else if(ctx.data) {
ctx.data.propertyName = propertyValue;
...
return next();
}
});
推荐阅读
- javascript - 反应地图运算符
- arrays - Powershell 将数组中的数据组合成一个对象
- python - 图片 PIL -“ValueError:波段索引超出范围”
- couchbase - Couchbase 5.5:为什么将 '\\' 放入 meta.id 会使搜索更快?
- javascript - 需要到达嵌套在数组 MongoDB 中的字段
- php - PHP Laravel - 下载额外大小的返回 ZIP 文件
- c# - 在 Mac 上的 Unity 中暂停和播放时使用 VideoPlayer 的平台特定音频延迟
- asp.net - 在 Web.Release.config 中转换连接字符串
- javascript - 使用 forEach 和 async/await,节点和 Jest 的行为不同
- javascript - Chrome 白名单扩展