Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

311
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!