Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
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) => {
        [...]
    })
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use a function

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

addLocationCondition(db.collection('posts'), location).get()...
about 4 years ago · Juan Pablo Isaza Relatório

0

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 => { 
    // ...
});
about 4 years ago · Juan Pablo Isaza Relatório

0

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) => {
   [...]
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda