Reputation: 123
I have this piece of code:
return User.findAll({where: {}, include:[
{model: UserInfo, where: {
gender: genderPreference
}}
]
I want to pass such a value in genderPreference so that it gives me all the values. Currently I'm passing either "Male" or "Female" which gives me that data from database accordingly; but if there is no preference for any of the genders then i have no idea on what to do. I have tried null, " " , "" ; but none of them work. Is there any solution to this? Thanks.
Upvotes: 1
Views: 1469
Reputation: 11
There's a much better way to achieve what you need here without the if/else clause
return User.findAll({where: {}, include:[
{
model: UserInfo,
where: req.body.genderPreference ? { gender: req.body.genderPreference } : {}
}
]
This allows the database search if the body is present, and returns all gender preference if the body isn't present. I believe this is a much cleaner code.
Upvotes: 1
Reputation: 123
I actually solved this with a different approach. Placing:
gender: null
actually searches if the gender field in the database is null or not, so I had to solve it with a different approach. I wanted "all the data" in the database. So, this pretty much solved it:
if(req.body.genderPreference == "none"){
conditionalUserInfo = {model: UserInfo, where:{}};
} else {
conditionalUserInfo = {model: UserInfo, where: {gender: req.body.genderPreference}};
}
return User.findAll({where: {}, include:[
conditionalUserInfo
]
GenderPreference parameter contains either 'Male' or 'Female' or 'none'.
Upvotes: 1
Reputation: 1
Just don't use quotes on null
, it'll work fine
return User.findAll({where: {}, include:[
{model: UserInfo, where: {
gender: null
}}
]
See the tutorial for more information
Upvotes: 0