我尝试在定义时只显示数组中的一个元素。例如,我的用户架构是:
var UserSchema = new mongoose.Schema({
username: { type: String, unique: true, required: true },
name: { type: String, required: true },
email: { type: String, unique: true, required: true },
password: String,
studio: { type: String, required: true },
comments: [
{
quantity: String,
received: { type: Date, default: Date.now },
collected: { type: String, default: "At Reception" }
}
],
isAdmin: { type: Boolean, default: false }
});
以下循环将列出所有用户,他们的电子邮件,姓名等:
<% for(var i=0; i < users.length; i++) { %>
<tr>
<td><%= users[i].studio %></td>
<td><%= users[i].name %></td>
<td><%= users[i].email %></td>
<td><%= users[i].comments %></td>
<% } %>
但users[i].comments
显示整个数组,我只希望它显示collected
元素 - 目前显示:
{
received: 2017-12-13T08:51:14.914Z,
collected: 'At Reception',
quantity: '5',
_id: 5a30ea0253432220138b4b89
}
我已经尝试了<td><%= users[i].comments.collected %></td>
,但这导致没有显示任何内容。
if
语句来过滤它们)。
答案 0 :(得分:0)
尝试<%= users[i].comments[0].collected %>
,评论[0]&lt; - 评论数组中的第一项
答案 1 :(得分:0)
您可以映射注释数组。我不确定是否有可能使用该模板语言,但在常规js中它将是:
users[i].comments.map((comment) => comment.collected)
编辑在ejs中包含一个例子
<% for(var i=0; i < users.length; i++) { %>
<% comments = user[i].comments.map(function(comment) {
return comment.collected;
}) -%>
<tr>
<td><%= users[i].studio %></td>
<td><%= users[i].name %></td>
<td><%= users[i].email %></td>
<td><%= comments %></td>
<% } %>