Sequelize Model Querying
From Logic Wiki
Contents
Model Querying - Finders
findAll
It generates a standard SELECT query which will retrieve all entries from the table (unless restricted by something like a where clause)
findByPk
const project = await Project.findByPk(123);
findOne
const project = await Project.findOne({ where: { title: 'My Title' } });
findOrCreate
it will return an instance (either the found instance or the created instance) and a boolean indicating whether that instance was created or already existed.
const [user, created] = await User.findOrCreate({
where: { username: 'sdepold' },
defaults: {
job: 'Technical Lead JavaScript'
}
});
findAndCountAll
The findAndCountAll method is a convenience method that combines findAll and count. This is useful when dealing with queries related to pagination where you want to retrieve data with a limit and offset but also need to know the total number of records that match the query.
The findAndCountAll method returns an object with two properties:
- count - an integer - the total number records matching the query
- rows - an array of objects - the obtained records
const { count, rows } = await Project.findAndCountAll({
where: {
title: {
[Op.like]: 'foo%'
}
},
offset: 10,
limit: 2
});
console.log(count);
console.log(rows);