I am doing my where clause outside the findAll() method to allow the user to send filter's or not in the request body. One of the values on my request body is categoryId that can be sent or not.
This is my code :
const where = {}
if (categoryId) {
where = { '$subcategories.category_id$': categoryId
}
}
try {
const establishments = await establishment.findAll({
attributes: [
"id",
"description",
"latitude",
"longitude",
[sequelize.literal(' (6371 * acos ( '
+ 'cos( radians(' + latitude + ') ) '
+ '* cos( radians( latitude ) ) '
+ '* cos( radians( longitude ) - radians(' + longitude + ') )'
+ '+ sin( radians(' + latitude + ') )'
+ '* sin( radians( latitude ))))'), 'distance']
],
include: [{
attributes: [],
model: subcategory, as: 'subcategories',
required: false,
},
{
attributes: ["id", "name"],
model: certificate, as: 'certificates',
required: false,
},
],
where: {
where
},
establishments: ['id'],
});
} catch (error) {
console.log(error)
res.status(400).json({ Error: "Error while fetching the establishment" });
}
Error given :
UnhandledPromiseRejectionWarning: TypeError: Assignment to constant variable.
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()