Search code examples
mysqlexpressroutesexpress-handlebars

Express-handlebars routing multiple data sets to one page


I have two mysql tables, one containing blogposts and one containing team members.

members:

    (...)
     class Members {
      static all (callback) {
        pool.getConnection((err, connection) => {
          if (err) throw err
          connection.query('SELECT * FROM members', (err, results, fields) => {
            callback(err, results)
            connection.release()
          })
        })
      }
    (...)
}
module.exports = pool
module.exports.Bposts = Members

Blog posts:

(...)
    class Bposts {
      static all (callback) {
        pool.getConnection((err, connection) => {
          if (err) throw err
          connection.query('SELECT * FROM bposts', (err, results, fields) => {
            callback(err, results)
            connection.release()
          })
        })
      }
(...)
}
module.exports = pool
module.exports.Bposts = Bposts

Both databases work fine and I'm able to add content to them though my admin page's forms.

I wish to add two lists on that page, one showing members already in the system, and another showing existing posts.

Problem is, I don't know how to route multiple data sets to the same page though express server.

app.get('/forms', (request, response, next) => {
  Members.all((err, members) => {
    if (err) return next(err)
    response.render('forms', {
      members: members
    })
  })
  Bposts.all((err, members) => {
    if (err) return next(err)
    response.render('forms', {
      bposts: bposts
    })
  })
})

^^ This dosn't work, and if i only route with Members data, i can't make a list of the blog posts too.

When doing as shown above i get an error saying that the server cant send multiple headers when the client has already received one - which dose make perfect sense. I'm just really confused as to how i should approach this.


Solution

  • Apparently I did not think hard enough, but here is the solution I found after sleeping on it:

    app.get('/forms', (request, response, next) => {
      Members.all((err, members) => { 
        if (err) return next(err) 
        Bposts.all((err, bposts) => {
          if (err) return next(err)
          response.render('forms', {
            members: members,
            bposts: bposts
          })
        })
      })
    })
    

    This allows me to access both datasets though handlebars on my admin page.