Home > other >  Sending through variables in `res.render` that are conditionally empty
Sending through variables in `res.render` that are conditionally empty

Time:03-26

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
    })
})

CodePudding user response:

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,
        })
    })
  • Related