如何使用Handlebars和NodeJS从MongoDB中显示所有用户

时间:2018-08-09 07:24:34

标签: javascript node.js express handlebars.js

我一直在尝试从服务器检索所有用户的信息,问题是未在检索该信息。我一直在尝试使用User.find(),也曾在尝试使用User.findOne,但是只能检索一个用户。目前,这是我的代码结构:

Dashboard.hbs:

{{#if user}}
<h1>Welcome {{user.firstname}}!</h1>
<h3>Account information:</h3>

<p>Full Name: {{user.firstname}} {{user.lastname}}</p>
<p>Usename: {{user.username}}</p>
<p>Email: {{user.email}}</p>
<p>Role: {{user.role}}</p>
<a href="/views/admin-views/edit-page.hbs">Edit Profile Information</a>
<br>
{{/if}}
<br>
{{#if user.isAdmin}}
<hr>
<h2>User List</h2>
<a href="/views/admin-views/edit-page.hbs">See User List</a>
<ul>
  {{#each userList}}
  <li>
    <h3>{{this.firstname}} {{this.lastname}}</h3>
    <ul>
      <li>User ID: {{this._id}}</li>
      <li>Username: {{this.username}}</li>
      <li>Email: {{this.email}}</li>
    </ul>
    <form action="/delete-user/{{this._id}}" method="post">
      <button>Delete User</button>
    </form>
  </li>
  {{/each}}
</ul>
<a href="/logout">Logout</a>
{{/if}}

这是JS代码,请注意,我有三种不同的状态(添加,删除和查找):

// Admin Accesses:
authRoutes.get('/dashboard', checkAdmin, (req, res, next) => {
  if (!req.user || req.user.role !== "ADMIN") {
    next();
    return;
  }
  User.find()
    .then((usersFromDb) => {
      res.locals.userList = usersFromDb;
      res.render('admin-views/admin-list-page');
    })
    .catch((err) => {
      next(err);
    });
});

authRoutes.post('/process-create-user', (req, res, next) => {
  const { firstname, lastname, username, email, password, role } = req.body;
  const salt = bcrypt.genSaltSync(10);
  if (password === "") {
    res.redirect('/dashboard');
    return;
  }
  User.create({ firstname, lastname, username, email, password, role })
    .then(() => {
      res.redirect('/dashboard');
    })
    .catch((err) => {
      next(err);
    });
});

authRoutes.post('/dashboard/:userId', (req, res, next) => {
  if (req.user.role === "ADMIN") {
    console.log("Cannot delete ADMIN");
    return;
  }
  let userId = req.params.userId;
  User.remove({ _id: userId })
    .then(() => {
      res.redirect('/admin-views/user-list');
    })
    .catch((err) => {
      next(err);
    });
});

如何正确配置它以使其显示在本地主机页面中?预先感谢!

0 个答案:

没有答案