Reputation: 3
I'm using mongoose and express, among other things. I can display the top level values, like "number", but i can't get "contact.email". I've tried a lot of options in my server.js file, but I'm hoping someone can help me extract this info from the json on the ejs side. Thanks!
I'm using this code in my ejs template:
`<% for(var i= 0 ; i < myObj.length; i++) {%>
<li>
<span><%=myObj[i].number %>
</li>
<% } %>
</ul>`
the schema
"_id" : ObjectId("5e67c84a65a2893029991863"),
"number" : 5,
"contact" : [
{
"_id" : ObjectId("5e69a33a0208203268813e01"),
"email" : "[email protected]",
}
]
}`
Upvotes: 0
Views: 329
Reputation: 4453
By Assuming that your object format is as below:-
var myObj= {
"_id" : ObjectId("5e67c84a65a2893029991863"),
"number" : 5,
"contact" : [{
"_id": ObjectId("5e69a33a0208203268813e01"),
"email": "[email protected]"
}]
};
You have to loop your data like as below:-
<span><%=myObj.number %></span>
<ul>
<% for(var i= 0 ; i < myObj.contact.length; i++) {%>
<li><%=myObj.contact[i].email %></li>
<% } %>
</ul>`
Note:- As myObj
is an object. and myObj.contact
is an array
of myObj
. so in this case you have to loop your myObj.contact
.
Upvotes: 0
Reputation: 1767
You can try this below since you need another loop for accessing the contact array in your json:
<% for(var i= 0 ; i < myObj.length; i++) {%>
<li>
<span><%=myObj[i].number %>
</li>
<ul>
for(var j=0 ; j < myObj[i].contact.length; j++)
<li>
<span><%=myObj[i].contact[j].email %>
</li>
<% } %>
</ul>
<% } %>
</ul>`
Upvotes: 0