Danjuro
Danjuro

Reputation: 141

Iterate through a MongoDB object's data

I will start off with how my mongoDB data looks like:

_id : 5c5b450918cb2b121648ff7a
name : "dannondarko"
email : "dangilmail@gmail.com"
password : "$2a$10$3z5m1e9Pcfid72Q2GchCjeTD55/SsIxmtWr3I1ZiA.DX/KlpfTbdK"
date : 2019-02-06 20:35:21.973
__v : 0
posts : Array
    0 : Object
        note : "test for the user dannondarko"
        date : "02/08/2019"

This is just a side project and most likely will never be live so don't worry about the security of me posting this data! As for how I am procession the code in my server code:

app.get('/:username', (req, res) => {
  username = req.params.username.toLowerCase();
  const collection = req.app.locals.collection;

  collection.find({ name: username }).toArray(function (err, results) {
    if (err) {
      res.status(500).send("Error communicating with the DB.");
    } else if (results.length > 0) {
      console.log("Here are the results: " + results);
      console.log({people: results});
      res.status(200).render('profile', {posts: results, name: username});
    } else {
      next();
    }
  });
});

What I am doing with this code is say you head to the address bar '/dannondarko', it should find 'dannondarko' in the collection, which it does fine, and then the 'results' variable is the complete object that I posted above. What I am trying to do is just get the 'posts' data, such as the note and date.

The note and date is the only data I need, which will be sent to this .ejs file that should create a post (kind of like FB) that shows the users' notes and date of the post. Here is my .ejs file:

<h1 class="mt-4"><%= name %></h1>
<div class="container">
  <br>
  <% for(var i=0; i < posts.length; i++) { %>
      <div class="container">
          <label><%= posts[i].note %></label>
        <div class="container">
          <label><%=  posts[i].date %></label>
        </div>
      </div>
  <% } %>
</div>

I hope that's enough information. I believe my downfall is not knowing how to just extract the 'posts' array from MongoDB from a certain user and iterate through the objects and sending over the note and date to the .ejs.

Upvotes: 0

Views: 239

Answers (1)

dimitris tseggenes
dimitris tseggenes

Reputation: 3186

The results is an array of documents and you render this array to ejs as posts. Now in your ejs file posts represent the array of documents, not the posts array. So if you want to loop through all results you should edit your code like this:

<% posts.forEach(post =>  { %>
<h1 class="mt-4"><%= post.name %></h1>
<div class="container">
  <br>
  <% post.posts.forEach(p =>  { %>
      <div class="container">
          <label><%= p.note %></label>
        <div class="container">
          <label><%=  p.date %></label>
        </div>
      </div>
  <% }) %>
</div>
<% }) %>

If i understand well your mongo model structure the above should help you.

Upvotes: 1

Related Questions