Home > Blockchain >  JAVASCRIPT for loop MONGODB
JAVASCRIPT for loop MONGODB

Time:11-11

I have a Mondodb query bringing back information from the database, the information brought comes as:

{
  _id: new ObjectId("623rf3f22275f399f88bb"),
  first_name: 'Are',
  last_name: 'You',
  email: '[email protected]',
  password: '$2a$10$BSmezAjYkqU.234t65sT1pPOhg5jxosYrFzwjqXM3On3v.b7p46K1WS',
  username: 'lcd1',
  Messages: [
    {
      msgcontent: 'The user whatever said: whatsup.'
    },
    {
      msgcontent: 'The user whatever said: whatsup.'
    },
    {
      msgcontent: 'The user whatever said: whatsup.'
    },
    {
      msgcontent: 'The user whatever said: whatsup.'
    },
    {
      msgcontent: 'The user whatever said: whatsup.'
    }
  ]
}

And I'm trying to show the total of messages on the page, and have already managed to display them, now what I need help with it looping through an iteration that leaves a simple number saying whats the message number like..(theres 5) Message 1, Message 2, Message 3 and so forth...

How can I do this?

I have tried:

    <% if (messages) { %>

            <% if (messages != "") { %>
                <% for (const { msgcontent } of messages) { %>
                <li><%  for (nr = 1; nr < messages.length; nr  ) { %><%= [nr] %><% }%>  <div ><%= msgcontent %></div></li>
                <% } %>
        <% } else if (messages == "") { %>
                <div ><%= "You currently have no messages." %></div>
            <% } %>
        <% } %>

which doesn't quite do it, leaving all 5 numbers displayed instead of one per message...

What should I do?

CodePudding user response:

Try with:

<% if (messages.length > 0) { %>
    <% for (let nr = 1; nr <= messages.length; nr  ) { %>
        <div ><%= [nr] %><%= messages[nr-1].msgcontent %></div></li>
    <% } %>
<% } else { %>
    <div >You currently have no messages.</div>
<% } %>
  • Related