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).
这篇关于用字符串而不是对象对返回数组进行续集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用字符串而不是对象对返回数组进行续集
基础教程推荐
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
