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
相关产品推荐
相关产品推荐

