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 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 在多列上分布任意行 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- oracle区分大小写的原因? 2021-01-01
