Categories
JavaScript Answers

How to use Sequelize findOne to find the latest entry?

Spread the love

Sometimes, we want to use Sequelize findOne to find the latest entry.

In this article, we’ll look at how to use Sequelize findOne to find the latest entry.

How to use Sequelize findOne to find the latest entry?

To use Sequelize findOne to find the latest entry, we can use the findOne method with the order property to order items by createdAt descending.

For instance, we write

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

to call findOne with an object with the order property that’s set to an array with ['createdAt', 'DESC'] to order the results by the createdAt value sorted in descending order.

And we use where to return the result with key set to key.

Conclusion

To use Sequelize findOne to find the latest entry, we can use the findOne method with the order property to order items by createdAt descending.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *