Justin Li
Justin Li

Reputation: 91

Passing json to EJS

I'm trying to pass data from my database to the client(EJS template). However, the data isn't outputting, and I'm not getting any errors doing so. So I tried to console.log the data to my terminal and it does show, it just does not show up on the ejs page.

Here's my code:

<div class="row">
    <!-- LOCAL INFORMATION -->
    <div class="col-sm-6">
        <div class="well">
            <h3><span class="fa fa-user"></span> Local</h3>

            <p>
                <strong>id</strong>: <%= user._id %><br>
                <strong>email</strong>: <%= user.local.username %><br>
                <strong>password</strong>: <%= user.local.password %><br />
                <strong>text</strong>: <%= text %>
            </p>
        </div>
    </div>

Here's the backend:

  app.get('/profile', isLoggedIn, (req, res) => {
    var text;
    MongoClient.connect("mongodb://localhost:27017/manage", (err, db) => {
      db.collection("data", (err, collection) => {
        collection.find().toArray((err, res) => {
          if(err){
            throw err;
          }
          text = res[0].string;
          console.log(text);
        });
      });
    });
    res.render('auth/profile', {
      user: req.user,
      text: text
    });
  });

Notice that there's a console.log(text) , and that does output the correct text to the terminal, I'm just having issues passing it through to the client. All the user's data outputs correctly as well.

Upvotes: 0

Views: 1534

Answers (1)

dzm
dzm

Reputation: 23534

You need to have your res.render within the callback of your query, for example:

 app.get('/profile', isLoggedIn, (req, res) => {
    var text;
    MongoClient.connect("mongodb://localhost:27017/manage", (err, db) => {
      db.collection("data", (err, collection) => {
        collection.find().toArray((err, response) => {
          if(err){
            throw err;
          }
          text = response[0].string;
          console.log(text);
          res.render('auth/profile', {
           user: req.user,
           text: text
          });
        });
      });
    });
  });

The way you have it setup now it's being executed before the callback is finished and its out of scope. Also, you generally don't want to put your database connection inside your routes. You would want to do one database connection when your node server starts, then pass that connection to your routes to re-use the connection, otherwise every time your route is hit, you're re-connecting to the db.

To add, you also wouldn't want to do throw err as this will stop your node process (I assume you're using express?). Instead just log the error or do a return and res.render and include the error so you can handle it in your view.

Edit:

In your callback for toArray you have to change the name of the response from res to response or anything other than res, so you don't override the server res object.

Upvotes: 2

Related Questions