Hamid Tanhaei
Hamid Tanhaei

Reputation: 39

Sequelize check whether query has result or not

I'm new in Sequelize and want to check to do something if my Select has any result.

this is my code to getting data using await and want to check the result to do something.

const result = await db.bookmark.findAll();

And I want to check if this query has a result or not. Something like this:

if(result){ /* do somthing */ } else { res.status(404) }

but always i get true becuase i'm checking the result as a model.

this is my way that works fine but I'm not sure whether it's the right way or not:

if(JSON.parse(JSON.stringify(result)) != false) // do something

is there any easy method or way to check resulted selects?

Upvotes: 1

Views: 7721

Answers (2)

Ibrahim Hammed
Ibrahim Hammed

Reputation: 880

I used findAndCountAll and check if the result.count is 0

Upvotes: 0

Nimish Gupta
Nimish Gupta

Reputation: 1051

findAll always return the result from the model. If the rows don't exist it returns an empty array. So

 if(result){ /* do somthing */ } else { res.status(404) }

the above statement will always return true. You can check for empty array if you want to return status 404, something like below

 if(result.length != 0){ /* do somthing */ } else { res.status(404) }

Upvotes: 5

Related Questions