我得到一个错误,我定义的数组没有定义

问题描述 投票:0回答:1
app.get("/", getLists, getItems, renderForm);

function getItems(req, res, next) {
  Item.find({}, function(err, foundItems) {
    if (foundItems.length === 0) {
      Item.insertMany(defaultItems, function(err) {
        if (err) next(err);
      });
      res.redirect("/");
    } else {
      console.log("foundItems" + foundItems);
      res.locals.listTitle = "Today";
      res.locals.newListItems = foundItems;
      next();
    }
  });
};

function getLists(req, res, next) {
  List.find({}, function(err, foundLists) {
    if (err) next(err);
    console.log("foundLists" + foundLists);
    res.locals.newLists = foundLists;
    next();
  });
};

function renderForm(req, res) {
  res.render("list");
};

我正在尝试使用 ejs、express、mongodb 和 node.js 制作待办事项列表。我想在导航栏中查看列表的名称。这就是为什么我写了上面的函数来获取项目和列表名称。

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">To-Do List</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <% newLists.forEach(function(list) { %>
          <li class="nav-item">
            <a class="nav-link" href="/"><%= list.name %></a>
          </li>
        <% }) %>
      </ul>
    </div>
  </div>
</nav>

我可以在渲染后和控制台中看到列表名称。但我仍然在控制台中出错。 newLists is not defined

我也获得了 500 的状态。伙计们,我该怎么办?

我尝试将列表和项目数组打印到控制台并查看它们。我已经将两个数组打印到控制台,但错误“newLists is not defined”仍然存在。

javascript node.js mongodb express ejs
1个回答
0
投票

newLists
getLists
中定义但在
renderForm

中不可用

要使 newLists 在

renderForm
中可用,您可以使用
res.locals
中的
getLists
对象来存储
foundLists

function getLists(req, res, next) {
  List.find({}, function(err, foundLists) {
    if (err) next(err);
    console.log("foundLists" + foundLists);
    res.locals.newLists = foundLists; // store foundLists in res.locals
    next();
  });
};

然后在

renderForm
中,您可以从
newLists
访问
res.locals

function renderForm(req, res) {
  res.render("list", res.locals); // pass newLists to the view
};

© www.soinside.com 2019 - 2024. All rights reserved.