【问题标题】:Loop through array field in schema mongoose遍历模式猫鼬中的数组字段
【发布时间】:2020-08-05 03:05:08
【问题描述】:

所以我有一个包含名称和部门的社区模式,部门字段有一个类型数组..如何根据名称字段在下拉列表中呈现部门。

这是我的 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" ]
}

我正在尝试制作一个依赖下拉列表,希望我的问题被理解

【问题讨论】:

  • 您能否在find 查询之后添加数据的结构方式.....只需console.log(data) 并在可能的情况下在此处添加示例数据
  • @RohitAmbre 我已经添加了示例数据。谢谢

标签: javascript node.js mongodb express ejs


【解决方案1】:

不要对您的阵列执行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>

.

(我的假设如下)

我不确定您的问题中的预期输出是什么,但我认为您在选择下拉列表中期望如下所示的内容,如果是,那么上面的代码不会给出结果。

|- 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>

【讨论】:

  • 很好用.. 但我想制作 2 个下拉列表,一个用于社区,另一个用于部门.. 部门下拉列表应取决于社区的价值
  • 为此,您必须更改代码的实现。而是将数据从路由传递到模板文件,进行 AJAX 调用以获取第一个下拉列表的列表,然后第一个下拉列表的 onChange 进行另一个 AJAX 调用以获取相关下拉列表。您将制作 2 个返回 JSON 的 API。例如检查这个question and answer
猜你喜欢
  • 2018-03-21
  • 1970-01-01
  • 2021-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
相关资源
最近更新 更多