You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sequelize findAll()返回顺序异常问题的排查与解决

Sequelize查询聊天消息排序异常问题及解决

我在使用Sequelize ORM获取聊天页面消息表数据时,遇到了排序异常的问题:返回结果按textcontent字段的字母顺序排列,而非预期的创建时间顺序。

原API代码

用于列出所有消息的REST API方法如下:

async index(req, res) {
    try {
      const message = await Text.findAll({
        attributes: ['id', 'msghour', 'created_at', 'useremail', 'textcontent'],
        order: [['textcontent', 'DESC'], ['useremail', 'DESC'],  ['created_at', 'DESC'],  ['id', 'DESC']],
      }); 
      return res.json(message);
    } catch (e) {
      return res.json(null);
    }
  }

问题现象

部分最新消息本该出现在列表末尾,却显示在前端顶部。

尝试过的无效方案

  • 仅按id降序排序:order: [['id', 'DESC']],
  • 所有字段升序排序:order: [['textcontent', 'ASC'], ['useremail', 'ASC'], ['created_at', 'ASC'], ['id', 'ASC']],
    以上两种调整都未能解决排序异常的问题。

解决过程及最终代码

排查后发现问题根源在于消息路由文件中的中间件,或是向服务器推送API更新的Git命令环节。最终有效的消息控制器代码如下:

async index(req, res) {
    try {
      const message = await Text.findAll({
        attributes: ['id', 'msghour', 'created_at', 'useremail', 'textcontent'],
        order: [['created_at', 'DESC']],
      });
      return res.json(message);
    } catch (e) {
      return res.json(null);
    }
  }

内容的提问来源于stack exchange,提问作者Lucas_0502

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 12:45:01