Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Keith Short
Keith Short
5,971 Points

Replacing elements on the webpage with node.js

I am making a web app which will query a database and display some data in a <table>.

As node.js is non-blocking, the entire webpage will have been created and response.end(); will have happened before the function that queries data from the database has finished.

As such I need to manipulate elements on the page once the query has finished.

I have a placeholder {{table}} on my html page, how will I replace this with my <table> filled with data from the database?

1 Answer

Jesus Mendoza
Jesus Mendoza
23,274 Points

You add the response inside the query for the database. Example:

app.get('/', function(req, res) {
   DbCollection.find(function(err, docs) {
      if (err) return console.log(err);

      res.render('index', { docs: docs });
   })
}

DbCollection is the name of your database model

Jesus Mendoza
Jesus Mendoza
23,274 Points

You can also make a local variable to use with your application where you do exactly the same but use it globally.

app.use(function(req, res, next) {
   DbCollection.find(function(err, docs) {
      if (err) {
         return console.log(err);
      } else {
         res.locals.VARIABLENAME = docs;
      }
      next();
   });

});

And now you can send that data from your routes as json with your render response