sails-dynamodb中按默认updatedAt字段排序数据的技术问询
按
updatedAt字段排序的解决方案 嘿,我来帮你搞定按updatedAt排序的需求!首先得说,你当前代码里的sort: "1"写法不对,从你的模型和Controller风格来看是用的Sails.js框架,它的sort参数需要明确指定排序字段和方向。
第一步:确认updatedAt字段存在
Sails.js默认会自动给所有模型添加createdAt和updatedAt这两个时间戳字段,不需要你手动在attributes里定义——除非你特意在模型里关闭了这个功能。如果没关的话,直接用就行。
第二步:修改Controller的排序参数
根据你想要的排序逻辑调整sort的值:
- 想按更新时间升序(最早更新的结果排在前面):可以写
sort: "updatedAt"或者sort: "updatedAt ASC" - 想按更新时间降序(最新更新的结果排在前面,这应该是你说的“默认创建并更新”的常用排序逻辑):可以写
sort: "updatedAt DESC"或者简化成sort: "-updatedAt"
修改后的完整Controller代码示例
Anuncio.find({ where: { category: request.category, subCategory: request.subCategory }, // 这里用降序,把最新更新的结果放在最前面 sort: "updatedAt DESC" }).exec((err, result) => { if (err) return next(err); return res.json(result); });
特殊情况:如果手动关闭了自动时间戳
要是你之前在模型里设置了autoCreatedAt: false或autoUpdatedAt: false,那得先手动把updatedAt字段加回去:
module.exports = { attributes: { id:{ type: "string", primaryKey: 'hash' }, title:{ type: "string", required: true }, category:{ type: "string", required: true }, subCategory:{ type: "string" }, // 手动添加updatedAt字段,支持date或时间戳类型 updatedAt: { type: 'date', autoUpdatedAt: true } }, // 确保自动时间戳功能开启 autoCreatedAt: true, autoUpdatedAt: true };
内容的提问来源于stack exchange,提问作者Gustavo García González
相关产品推荐
相关产品推荐

