Sequelize return array with Strings instead of Objects(用字符串而不是对象对返回数组进行续集)
问题描述
有时我只想从多行中选择一个值.
Sometimes i only want to select a single value from multiple rows.
假设我有一个如下所示的帐户模型:
Lets imagine i have an account model which looks like this:
帐户
- 身份证
- 姓名
- 年龄
我只想选择名字.
你会这样写:
AccountModel.findAll({
where: {
Age: {
$gt : 18
}
},
attributes: ['Name'],
raw : true
});
但这会返回一个带有对象的数组.
But this would return in an array with objects.
[{Name : "Sample 1"}, {"Name" : "Sample 2"}]
我想得到一个只有这样名字的数组:
I would like to get an array with only names like this:
["Sample 1", "Sample 2"]
是否可以通过 Sequelize 实现这一目标?我已经搜索了文档但找不到它.
Is it possible to achieve this with Sequelize? I've searched trough the documentation but couldn't find it.
推荐答案
使用 Sequelize 3.13.0 似乎不可能让 find 返回一个平面数组而不是数组对象.
Using Sequelize 3.13.0 it looks like it isn't possible to have find return a flat array of values rather than an array of objects.
解决问题的一种方法是使用下划线或 lodash 映射结果:
One solution to your problem is to map the results using underscore or lodash:
AccountModel.findAll({
where: {
Age: {
$gt : 18
}
},
attributes: ['Name'],
raw : true
})
.then(function(accounts) {
return _.map(accounts, function(account) { return account.Name; })
})
我已经上传了一个脚本来演示这个 这里.
I've uploaded a script that demonstrates this here.
作为快速说明,设置 raw: true 会使 Sequelize 查找方法返回普通的旧 JavaScript 对象(即没有实例方法或元数据).这可能对性能很重要,但不会更改转换为 JSON 后的返回值.这是因为 Instance::toJSON 总是返回一个普通的JavaScript 对象(无实例方法或元数据).
As a quick note, setting raw: true makes the Sequelize find methods return plain old JavaScript objects (i.e. no Instance methods or metadata). This may be important for performance, but does not change the returned values after conversion to JSON. That is because Instance::toJSON always returns a plain JavaScript object (no Instance methods or metadata).
这篇关于用字符串而不是对象对返回数组进行续集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用字符串而不是对象对返回数组进行续集
基础教程推荐
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
