【发布时间】:2019-02-10 03:58:21
【问题描述】:
我将从我的 mongoDB 数据的样子开始:
_id : 5c5b450918cb2b121648ff7a
name : "dannondarko"
email : "dangilmail@gmail.com"
password : "$2a$10$3z5m1e9Pcfid72Q2GchCjeTD55/SsIxmtWr3I1ZiA.DX/KlpfTbdK"
date : 2019-02-06 20:35:21.973
__v : 0
posts : Array
0 : Object
note : "test for the user dannondarko"
date : "02/08/2019"
这只是一个附带项目,很可能永远不会上线,所以不要担心我发布这些数据的安全性!至于我是如何处理服务器代码中的代码的:
app.get('/:username', (req, res) => {
username = req.params.username.toLowerCase();
const collection = req.app.locals.collection;
collection.find({ name: username }).toArray(function (err, results) {
if (err) {
res.status(500).send("Error communicating with the DB.");
} else if (results.length > 0) {
console.log("Here are the results: " + results);
console.log({people: results});
res.status(200).render('profile', {posts: results, name: username});
} else {
next();
}
});
});
我对这段代码所做的是,假设您前往地址栏“/dannondarko”,它应该在集合中找到“dannondarko”,这很好,然后“results”变量是完整的对象我在上面发过。我要做的只是获取“帖子”数据,例如注释和日期。
注释和日期是我需要的唯一数据,它们将被发送到这个 .ejs 文件,该文件应该创建一个帖子(有点像 FB),显示用户的注释和帖子的日期。这是我的 .ejs 文件:
<h1 class="mt-4"><%= name %></h1>
<div class="container">
<br>
<% for(var i=0; i < posts.length; i++) { %>
<div class="container">
<label><%= posts[i].note %></label>
<div class="container">
<label><%= posts[i].date %></label>
</div>
</div>
<% } %>
</div>
我希望这是足够的信息。我相信我的失败是不知道如何从某个用户的 MongoDB 中提取“帖子”数组并遍历对象并将注释和日期发送到 .ejs。
【问题讨论】:
标签: node.js mongodb express ejs