title: Express pass values in route to view with ejs
body: <p>This is my post route:</p>
  
  <pre><code>// CRUD posts.
  app.post('/crud', function(req, res) {
    db.users.addPost(req.body);
    res.redirect('crud')
  });
  </code></pre>
  
  <p>This is my get route:</p>
  
  <pre><code>app.get('/crud', function(req, res) {
    res.render('crud', {
      user: req.user,
      posts: db.users.retrievePost()
    });
  });
  </code></pre>
  
  <p>This is the function I use to retrieve posts from my database:</p>
  
  <pre><code>// Retrieve posts from database to pass to view.
  exports.retrievePost = function() {
    var cursor = postsCollection.find().toArray(function(err, record) {
      console.log(record);
      return record;
    });
  }
  </code></pre>
  
  <p>When I log record, it returns the following data:</p>
  
  <pre><code>[ 
    { _id: 57cb835ba8b8250bdcd65e5d, userCreate: 'This is a question' },
    { _id: 57cb85709435720c055b10e6, userCreate: 'hello' },
    { _id: 57cb87b10dc3ec0c3a78f970, userCreate: 'hello' },
    { _id: 57cb87c20dc3ec0c3a78f971, userCreate: 'what up here' } 
  ]
  </code></pre>
  
  <p>This is how I'm using ejs to display the userCreate values in my 'crud' view.</p>
  
  <pre><code>&lt;ul class="posts"&gt;
    &lt;% for(var i=0; i&lt;posts.length; i++) { %&gt;
    &lt;li class="post"&gt;
      &lt;span&gt;&lt;%= posts[i].userCreate %&gt;&lt;/span&gt;
    &lt;/li&gt;
    &lt;% } %&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p><strong>The error is:</strong>
  Cannot read property 'length' of undefined.</p>
  
  <p>Why would posts be undefined? In my get route when I rendered the view, I assigned the value of retrievePost() to posts. I then called on posts from that view that was rendered. We can assume that the function is exported properly because I use other functions from that same file in the same routes file. What is wrong here?</p>
  
  <p>I would like to add to this post the fact that I tested passing </p>
  
  <pre><code>title : "testing"
  </code></pre>
  
  <p>and was able to render it in the following way:</p>
  
  <pre><code>&lt;%= title %&gt;
  </code></pre>
  
  <p>So I'm really not sure why posts won't work.</p>