Reputation: 1492
Let's say I got a mongoose model and a value that is chance-based
const findUser = async (username, email) => {
let foo = null
if (Math.random() > 0.5) foo = "hi" // `foo` now has a chance of turning from null to "hi"
UserModel.find({ "username": username, "email": email, "winner": foo === null ? 'EXCLUDE THIS SEARCH VALUE' : foo
}
^ This is some real code, in combination with some pseudo code ^
I can achieve it like this:
const findUser = async (username, email) => {
let foo = null
if (Math.random() > 0.5) foo = "hi" // `foo` now has a chance of turning from null to "hi"
let result;
if(foo === null)
result = await UserModel.find({ "username": username, "email": email });
else
result = await UserModel.find({ "username": username, "email": email, "winner": foo });
// ^^ Now I have to type the same thing all over again..
// I'm wondering if there is a way to include it conditionally?
}
But the problem here is that I have to type the same thing again, just to include another field. Is there a way to condionally include a column in your search?
Upvotes: 1
Views: 61
Reputation: 507
You could extract your query to a variable, and then manipulate that based on the value of foo
.
const findUser = async (username, email) => {
let foo = null
if (Math.random() > 0.5) foo = "hi"
const query = { username, email }
if (foo) {
query.winner = foo
}
const result = await UserModel.find(query)
}
Upvotes: 1
Reputation: 1584
There may be an easier/better way to achieve this, but something I would do in this scenario is build out an object like this.
const findUser = async (username, email) => {
let foo = null
let query = {
username,
email
}
if (Math.random() > 0.5) foo = "hi" // `foo` now has a chance of turning from null to "hi"
if (foo != null) {
query.winner = foo;
}
UserModel.find(query);
}
Essentially, create a default object with your properties in it that will always be there. Then check if your foo value is not null. And if it's not null, then add it to your query and pass that query object in to the find.
Upvotes: 1