Friendly Mushroom
Friendly Mushroom

Reputation: 205

Is it possible to add a method dynamically in Javascript?

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) => {
        [...]
    })

Upvotes: 0

Views: 61

Answers (3)

enapupe
enapupe

Reputation: 17059

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) => {
   [...]
})

Upvotes: 1

Barmar
Barmar

Reputation: 782574

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 => { 
    // ...
});

Upvotes: 1

Yury Tarabanko
Yury Tarabanko

Reputation: 45106

You can use a function

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

addLocationCondition(db.collection('posts'), location).get()...

Upvotes: 2

Related Questions