我将从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的“posts”数组,并迭代这些对象,然后将注释和日期发送给.ejs。