typescript - elasticsearch 和 typescript - 将结果绑定到模型
问题描述
我想让我的 elasticsearch api 尽可能接近我的模型。我想在客户端和服务器中享受强类型的好处。
我有一个客户模型:
export interface CustomerBody{
name?: string;
}
export class CustomerModel implements IElModel<CustomerBody>{
readonly index: string = "db";
readonly type: string = "customer";
id: string;
body: CustomerBody = {}
}
保存此文档后,我运行一个查询,该查询具有不同的字段映射(与 mongodb 不同)。
数据库的结果是:
"hits": [
{
"_index": "db",
"_type": "customer",
"_id": "pVM963UBtjK7RM81ZgIx",
"_score": 1,
"_source": {
"name": "test"
}
},
{
"_index": "db",
"_type": "customer",
"_id": "p1NB63UBtjK7RM81kQIv",
"_score": 1,
"_source": {
"name": "test3111111"
}
}
]
使用 nodejs 驱动程序,如何将此结果绑定到CustomerModel[]
?
如果我设法做到这一点,我的大部分逻辑将是强类型的。
谢谢
解决方案
我自己解决了类似的情况。我的解决方案是将 hits 数组映射到我的界面中,在您的情况下是一个类。
const models: CustomerModel[] = hits.map(hit => {
const customer = new CustomerModel();
customer.id = hit._id;
customer.body = hit._source;
return customer;
});
推荐阅读
- python - Django 在创建/编辑新实例时运行函数,并让函数更改创建/编辑的实例中的变量
- excel - VBA:我怎样才能连接这个
- r - 如何匹配列的两个字符串并过滤匹配的列值
- javascript - 如何使用 Highcharts-Regression 获得方程值结果?
- c++ - 给定两个偶数,求它们之间所有偶数的平方和
- arduino - 如何不返回中断前程序停止的地方
- ruby-on-rails - 将rails应用程序部署到heroku时如何解决错误
- mysql - 使用 MySQL 中的临时表规范化数据
- python - 尝试在 IntelliJ 中构建 Jenkins 性能插件时出错
- unity3d - 如何在循环平滑的原始图像上播放视频文件?