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

312
Visualizações
Sending through variables in `res.render` that are conditionally empty

I'm trying to send through multiple variables into a res.render but I'm unsure of how to do it without an undefined error. Either one or the other will have an object to pass through but never both at the same time. Here's my current code that will give an undefined error.

app.get('/', async (req, res) => {
if (req.query.search) {
    const search = req.query.search
    const regex = new RegExp(search, 'i')
    const searchedblogposts = await BlogPost.find({title: {$regex: regex}})
    console.log(searchedblogposts)
} else {
    const blogposts = await BlogPost.find({})
}

res.render('index', {
    blogposts,
    searchedblogposts
    })
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Well, this is because one of blogPosts or searchBlogPosts remains undefined at any point of time and you're passing both in res.render . What you can do is this:

app.get('/', async (req, res) => {
let blogPosts;
if (req.query.search) {
    const search = req.query.search
    const regex = new RegExp(search, 'i')
    blogPosts = await BlogPost.find({title: {$regex: regex}})
} else {
    blogposts = await BlogPost.find({})
}

res.render('index', {
    blogposts,
    })
})

OR this:

 app.get('/', async (req, res) => {

const blogPosts = req.query.search? await BlogPost.find({title: {$regex: new RegExp(req.query.search, 'i')}}) 
: await BlogPost.find({})
    
    res.render('index', {
        blogposts,
        })
    })
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