1

I have an HTML table populated with MongoDB data. I used mongoose timestamps to display a date and time for any time a DB entry is updated.

I only want the most recent date/time to be displayed, instead of a date/time for each entry that gets updated (which is currently happening because of the forEach loop).

I'm not super familiar with mongoose so I'm wondering if there's a way to check for the most recent <%= environment.updatedAt %> and only display that one?

HTML:

<table>
   <% environments.forEach(function(environment){ %>

    <%= environment.updatedAt =>

     <tr>
         <td><%= environment.ePIMS %></td>
         <td><%= environment.codeVersion %></td>
         <td><%= environment.region %></td>
     </tr>

   <% }); %> 
 </table>

let me know if you'd like to see my mongoose schema or anything else. thanks!!

Emily
  • 391
  • 4
  • 21

1 Answers1

1

If you want to display the most recent updateAt after the table, assign it to a variable during the loop, and display it later. Assuming updateAt is numeric, that might look like

<%= newest = Math.max(newest, environment.updatedAt) =>

If you want the most recent time to be displayed first, or in each row, one option is to find the newest with reduce like

<%=  environments.reduce(function(a,v){return Math.max(a,v.updatedAt)},0) =>

Or you could sort the query by updateAt: -1 when retrieving the data so the newest is the first element.

Joe
  • 25,000
  • 3
  • 22
  • 44
  • thank you!! I went withsorting by ```updatedAt: -1``` to get the first one to always be the latest. I used https://stackoverflow.com/a/31824896/11099263 as a reference for how to sort in mongoose, if anyone was wondering – Emily May 05 '20 at 21:23