Sequelize findOne latest entry

Javascriptnode.jssequelize.js

Javascript Problem Overview


I need to find the latest entry in a table. What is the best way to do this? The table has Sequelize's default createdAt field.

Javascript Solutions


Solution 1 - Javascript

model.findOne({
    where: { key },
    order: [ [ 'createdAt', 'DESC' ]],
});

Solution 2 - Javascript

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]
}); 

Solution 3 - Javascript

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNoahView Question on Stackoverflow
Solution 1 - JavascriptszymView Answer on Stackoverflow
Solution 2 - JavascriptKrzysztof SztompkaView Answer on Stackoverflow
Solution 3 - JavascriptNoor Ul AinView Answer on Stackoverflow