[英]Loop through array field in schema mongoose
所以我有一个包含名称和部门的社区模式,部门字段有一个类型数组..如何根据名称字段在下拉列表中呈现部门。
这是我的 routes.js
router.get('/setup', (req, res,next) => {
Community.find(function(err, data) {
res.render('setup', {
community: data,
});
});
});
这是我的社区模式
const CommunitySchema = new mongoose.Schema({
name: {
type: String
},
department: [{
type: String
}]
});
这是我的 setup.ejs
<label for="fullname"><strong>What department do you belong to ?</strong></label>
<select class="form-control" id="community" name="community">
<optgroup label="Select Table">
<% community.forEach(function (practice) { %>
<option > <%= practice.department.pop() %> </option>
<% }) %>>
</optgroup>
</select>
**这是数据**
{
"name":"Engineering",
"departments":[ "Electrical engineering", "Mechanical engineering", "Chemical engineering" ]
},
{
"name":"Arts",
"departments":[ "Philosophy", "Theatre arts", "English" ]
}
我正在尝试制作一个依赖下拉列表,我希望我的问题得到理解
不要对你的数组执行pop
操作,
尝试这种方式,代码可能会产生语法错误,但想法是您应该遍历departments
数组以在select
元素内创建选项。
<label for="fullname"><strong>What department do you belong to ?</strong></label>
<select class="form-control" id="community" name="community">
<optgroup label="Select Table">
<% community.forEach(function (practice) { %>
<% practice.departments.forEach(function (dept) { %>
<option> <%= dept %> </option>
<% }) %>>
<% }) %>>
</optgroup>
</select>
.
(我的假设如下)
我不确定你的问题中预期的 output 是什么,但我认为你在 select 下拉列表中期待类似下面的内容,如果是,那么上面的代码不会给出结果。
|- Engineering
|--- Electrical engineering
|--- Mechanical engineering
|--- Chemical engineering
|- Arts
|--- Philosophy
|--- Theatre arts
|--- English
使用以下
<label for="fullname"><strong>What department do you belong to ?</strong></label>
<select class="form-control" id="community" name="community">
<% community.forEach(function (practice) { %>
<optgroup label="<%= practice.name %>">
<% practice.departments.forEach(function (dept) { %>
<option> <%= dept %> </option>
<% }) %>>
</optgroup>
<% }) %>>
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.