Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

313
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda