sequelize.js - 修改 findOne 函数返回的数据
问题描述
我用 db 创建了 get config 函数。我在我的服务器上使用了续集。
async function getConfig(country) {
return await db.config.findOne({
where: { id: 1 },
include: [
{
model: db.domain,
attributes: ['domain'],
as: 'domain',
where: {
country_code: country,
isActive: true,
},
},
{
model: db.currency,
attributes: ['id', 'code'],
},
{
model: db.task,
attributes: ['name'],
as: 'name',
where: {
isActive: true,
},
},
],
});
}
这个函数返回一个结果。
"result": {
"id": 1,
"is_show": false,
"version": "1.4.5",
"domain": [
{
"domain": "https://....."
}
],
"currencies": [
{
"id": 1,
"code": "USD",
"symbol": "$",
},
{
"id": 6,
"code": "USD",
"symbol": "$",
}
],
"name": [
{
"name": 123
}
]
}
我需要修改这个结果,我想得到这个结果
"result": {
"id": 1,
"is_show": false,
"version": "1.4.5",
"domain": "https://.....",
"currencies": [
{
"id": 1,
"code": "USD",
"symbol": "$",
},
{
"id": 6,
"code": "USD",
"symbol": "$",
}
],
"name": 123,
}
我尝试使用 operator 来做到这一点raw: true
。但它没有成功。
{
model: db.task,
attributes: ['name'],
as: 'name',
raw: true,
where: {
isActive: true,
},
},
我该怎么做?
回复
"result": {
"id": 1,
"is_show": false,
"version": "1.4.5",
"domain": [
{
"0": "h",
"1": "t",
"2": "t",
"3": "p",
"4": "s",
"5": ":",
"6": "/",
"7": "/",
"8": ".",
"9": ".",
"10": ".",
"11": ".",
"12": "."
}
],
"currencies": [
{
"id": 1,
"code": "USD",
"symbol": "$",
},
{
"id": 6,
"code": "USD",
"symbol": "$",
}
],
"name": [
{
"name": 123
}
]
}
解决方案
如果您希望从包含的模型中获取某些字段作为主模型的属性,您可以将其添加到主attributes
选项中,如下所示(domain
如下所示):
return await db.config.findOne({
where: { id: 1 },
attributes: { include: [[sequelize.col('domain.domain'), 'domain']] },
include: [
{
model: db.domain,
attributes: [],
as: 'domain',
where: {
country_code: country,
isActive: true,
},
},
{
model: db.currency,
attributes: ['id', 'code'],
},
{
model: db.task,
attributes: ['name'],
as: 'name',
where: {
isActive: true,
},
},
],
});
推荐阅读
- elasticsearch - 将弹性搜索范围查询与过滤器相结合,以排除其他字段上的空值
- java - 在 Tomcat 或 Wildfly 中使用 Java Web 应用程序进行多租户
- php - 尝试在 Laravel 8 中读取 null 的属性“权限”
- javascript - 从日历 ID 中拆分 base64 编码的事件 ID 并获取该事件的开始时间?
- graphql - 从 graphql 模式生成 proto3 文件
- go - String() 字符串到底是做什么的?
- python - 如何正确保存图形?我保存后这个图什么都没有了
- bash - 如何使用 bash 变量作为 awk 输入文件
- php - 使用通配符、范围和术语进行 Elasticsearch 搜索
- web-scraping - IMPORTXML:查询第一个 Google 搜索结果时“导入的内容为空”