首页 > 解决方案 > 将数据从数据库传递到 ejs 文件时,ejs 文件中的 forEach 错误

问题描述

我的数据以集合名称“user”存储在数据库中,但是当我尝试从数据库中获取数据并尝试使用 ejs 显示时。有时它显示我找不到数据,或者现在它显示 forEach 不是一个函数。甚至我为此安装了所有必要的模块。

Here is my app.js code

app
  .route("/newCandidate")
  .get(function (req, res) {
    res.locals.title = "New Candidate";
    if (req.isAuthenticated()) {
      console.log("registration done!");
      res.render("newCandidate");
    } else {
      res.render("login");
    }
  })
  .post(function (req, res) {
    console.log("working candidate status");
   

    var {

      name,
      email,
      mobile,
      offerIssued,
      offerDate,
      offerDoc,
      packageOffered,
      joiningBonus,
      joiningDate,
      isVerified

    } = req.body;
    console.log(req.body);

    var data = req.body;
    var isVerified = true;

    User({
      name,
      email,
      mobile,
      offerIssued,
      offerDate,
      offerDoc,
      packageOffered,
      joiningBonus,
      joiningDate,
      isVerified,
    }).save((err,data) =>{
      if(err){
        console.log(err);
      }else{
        console.log(req.body);
        res.locals.title = "List Status";
        res.render("listStatus");
      }
      
    });
   
  });

  app.get("/listStatus",function (req, res) {
    var data = User(req.body).save(function(err,item){
      if(err)console.log(err);
      res.locals.title = "List Status";
      res.render("listStatus",{item:data});
    });
 });


Here is my ejs file code

  <% item.forEach(function(items){ %>
          <tr>
          <th scope="col"><%=items.name%></th>
          <th scope="col"><%=items.email%></th>
          <th scope="col"><%=items.mobile%></th>
          <th scope="col"><%=items.offerIssued%></th>
          <th scope="col"><%=items.offerDate%></th>
          <th scope="col"><%=items.offerDoc%></th>
          <th scope="col"><%=items.packageOffered%></th>
          <th scope="col"><%=items.joiningBonus%></th>
          <th scope="col"><%=items.joiningDate%></th>
          <tr>
      <%  }); %>

在这个 ejs 文件中,我使用 item 来存储数据,并在 js 文件中创建对象和值,它可以从数据库中获取值。

标签: node.jsejs

解决方案


问题是您的逻辑完全错误。

当您打电话时,User.save您将获得一份代表您正在打电话的用户的文件item。然后在您的回调中,您将返回一个带有键的对象,该键也被调用item,并且您将其值设置data为未定义的值。

ejs 中的代码抱怨这forEach不是一个函数,因为不知何故您希望item传递给您的模板是一个数组,但实际上它是undefined.

即使您在处理程序中将其更改为

res.render("listStatus",{item: item});

这可能是您想要做的,您仍然无法调用forEach,因为item在这种情况下将是单个用户(您刚刚保存的那个),而不是一组用户。

如果你想保存用户然后渲染所有用户,你需要先保存用户,等到它被保存,然后再次调用你的数据库来获取所有用户并将它们发送到模板。

就像是

app.get("/listStatus", async function (req, res) {
    // omitting error handling for the sake of clarity
    
    await User(req.body).save();

    const users = await User.find({});

    return res.render("listStatus", { users });
}

// and in the ejs
<% users.forEach(function(user){ %>
    ...

推荐阅读