遍历模式猫鼬中的数组字段

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>

.

(以下是我的假设)

我不确定你的问题中预期的输出是什么,但我认为你在 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>