0

Hey I am making a firebase database call that looks like this:

db.collection("posts").where("location", "==", location)
    .get().then((querySnapshot) => {
        [...]
    })

The user can specify from what countries he would like to get posts (the .where() method is for that). But he can also pick all the countries, so in that case the method is no longer needed. Is there a way to add methods dynamically?

Something like this:

db.collection("posts")if(location != "all"){.where("location", "==", location)}
    .get().then((querySnapshot) => {
        [...]
    })
1
  • Just put the function call inside a condition: let query = db.collection(...); if (...) query = query.where(...); query.get().then(...) Commented Oct 4, 2021 at 19:22

3 Answers 3

2

You can use a function

const addLocationCondition = (collection, location) => 
    location === "all" ? collection : collection.where('location', '==', location);

addLocationCondition(db.collection('posts'), location).get()...
Sign up to request clarification or add additional context in comments.

2 Comments

A shorter alternative than an if statement, as well as a cleaner alternative to the other answers. I like it!
@Reality "Make const not var". :) It will look even better if/when this proposal got adopted github.com/tc39/proposal-pipeline-operator db.collection('post') |> addLocationCondition(#, location) |> #.get() |> await
1

No, you can't put a conditional there.

Just use if to decide whether to call .where().

let posts = db.collection("posts");
let filtered;
if (location == "all") {
    filtered = posts;
} else {
    filtered = posts.where("location", "==", location);
}
filtered.get().then(querySnapshot => { 
    // ...
});

Comments

1

I'm not completely sure about this db API but this should work:

let query = db.collection("posts")
if(location != "all"){
  query = query.where("location", "==", location)
}
query.get().then((querySnapshot) => {
   [...]
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.