EJS For 循环和 If 语句未显示正确的值

EJS For loop and If statement are not displaying the right value

我正在构建一个应用程序,允许用户单击一个按钮,当他们 return 进入页面时,它会显示一条消息“已经感兴趣”。当我显示页面时,它会跳过 for 循环中的 if 语句并显示 else 语句。我做错了什么?

下面是我的代码和当前输出。

<% for(var i=0; i < userInterests.length; i++) { %>
   <% if ((username == userInterests[i].username)  && (postID == userInterests[i].post_id)){ %> 
      <p>Already interested</p>
      <% break; %> 
   <% } else { %> 
      <form action="/jobs/interested/<%= post._id %>" method='POST'>
         <button type="submit" class="btn btn-info">I'm interested</button>
      </form>
      <% break; %> 
   <% } %> 
<% } %>

current output

MongoDB entry

逻辑问题,您仅使用 userInterests[0].username 和 serInterests[0].post_id 的值测试用户名和 postID,因为您有中断;在您的 2 个条件中声明,这是问题的解决方案:

<% var userInterested = false %> 
<% for(var i=0; i < userInterests.length; i++) { %>
   <% if ((username == userInterests[i].username)  && (postID == userInterests[i].post_id)){ %> 
          <% userInterested = true; %>
          <% break; %> 
   <% } %>
<% } %>
<% if (userInterested) { %> 
   <p>Already interested</p>
<% } else { %> 
   <form action="/jobs/interested/<%= post._id %>" method='POST'>
      <button type="submit" class="btn btn-info">I'm interested</button>
   </form>
<% } %>