[英]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.