node.js - 在nodejs中 Sequelize findAll排序顺序

标签 node.js express sequelize.js

我正在尝试使用 sequelize 从数据库中输出所有对象列表,如下所示,并希望在 where 子句中添加 id 时对数据进行排序。

exports.getStaticCompanies = function () {
    return Company.findAll({
        where: {
            id: [46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680]
        },
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']
    });
};

但问题是渲染后,所有数据整理如下。

46128, 53326, 2865, 1488, 45600, 61680, 49569, 1418, ....

我发现,它既不是按 id 也不是按名称排序的。请帮我解决一下。

最佳答案

在 sequelize 中,您可以轻松添加 order by 子句。

exports.getStaticCompanies = function () {
    return Company.findAll({
        where: {
            id: [46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680]
        }, 
        // Add order conditions here....
        order: [
            ['id', 'DESC'],
            ['name', 'ASC'],
        ],
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']
    });
};

看看我是如何添加对象的 order 数组的?

order: [
      ['COLUMN_NAME_EXAMPLE', 'ASC'], // Sorts by COLUMN_NAME_EXAMPLE in ascending order
],

编辑:

.then() promise 中收到对象后,您可能必须对其进行排序。查看这个关于根据自定义顺序对对象数组进行排序的问题:

How do I sort an array of objects based on the ordering of another array?

关于node.js - 在nodejs中 Sequelize findAll排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36259532/

相关文章:

javascript - 自动完成完成后隐藏输入字段

javascript - 我可以在express中编写app.get来动态获取吗?

node.js - 使用 NPM 打包和分发 Bash 脚本,以便使用 npm install 全局安装到开发人员工作站的路径中

node.js - 使用 Gmail API 从 Express 端点响应 JSON 对象

html - 在没有 Express 模板引擎的情况下向 HTML 添加值?

mysql - 使用 docker-compose 进行 Sequelize 迁移时出现 ECONNREFUSED 错误

mysql - node-mysql 一个查询中的多个语句

node.js - heroku Postgres - Sequelize 主机的 : no pg_hba. conf 条目

node.js - 如何在 Class 方法的模型中导入其他 Sequelize 模型。 Sequelize v 5

node.js - 无法从 angular.js 向express.js 发送 POST