序列化 findOne 最新条目

我需要在表格中找到最新的条目。最好的方法是什么?该表具有 Sequelize 的默认 createdAt字段。

107419 次浏览

Method findOne is wrapper for findAll method. Therefore you can simply use findAll with limit 1 and order by id descending.

Example:

YourModel.findAll({
limit: 1,
where: {
//your where conditions, or without them if you need ANY entry
},
order: [ [ 'createdAt', 'DESC' ]]
}).then(function(entries){
//only difference is that you get users list limited to 1
//entries[0]
});
model.findOne({
where: { key },
order: [ [ 'createdAt', 'DESC' ]],
});

If someone has turned timestamps false, you can do it with id too. This one worked for me.

model.findOne({
order: [ [ 'id', 'DESC' ]],
});