i have a controller and i want to make pagination with 5 records per page. How can i do it with Nodejs i really need help.
const getPagination = (page, size) => {
const limit = size ? size : 5; // Fetch 5 records
const offset = page ? page * limit : 0;// Start from page 0
return { limit, offset };
};
// Find all car with condition and how can i add pagination ?
export function findAllCar( req, res){
const name = req.query.name;
const color = req.query.color;
const brand = req.query.brand;
var condition = name ? {
name: { [Op.iLike]: `%${name}%` },
color: { [Op.iLike]: `%${color}%` },
brand: { [Op.iLike]: `%${brand}%` },
} : null;
Car.findAll({ where: condition })
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving CARS."
});
});
}
CodePudding user response:
you need to add limit and offset inside the query.
var condition = name ? {
name: { [Op.iLike]: `%${name}%` },
color: { [Op.iLike]: `%${color}%` },
brand: { [Op.iLike]: `%${brand}%` },
} : null;
const paginate = (query, { page, pageSize }) => {
const offset = page * pageSize;
const limit = pageSize;
return {
...query,
offset,
limit,
};
};
model.findAll(
paginate(
{
where: condition
},
{ page, pageSize },
),
);
Also, you can refer to this here
CodePudding user response:
you can use this
model.findAll({
limit: 5,
offset: 0,
where: {}, // conditions
});