【发布时间】:2022-01-04 16:21:43
【问题描述】:
我目前正在学习 node.js,这是我在其中的第一个项目。它(据说)是一个简单的待办事项列表应用程序,我可以在其中加载/编辑/保存/删除多个列表。
在 todo_list.ejs 文件中,我有一个 div,其中列出了所有集合名称:
<div id="list_container" class="lists">
<ul id="col_list" class="collection-list">
<% lists.forEach(list => { %>
<li class="collection-list-item">
<div class="list-name-container">
<a href="/<%=list.name %>" class="list-link">
<span class="list-name" name="list_name"><%=list.name %></span>
</a>
</div>
</li>
<% }) %>
</ul>
</div>
当我单击列表的链接时。我尝试使用以下代码加载新列表(这是一个 mongodb 集合):
app.route("/:list_name").get((req, res) => {
MongoClient.connect(process.env.DB_CONNECT, (err, db) => {
if(err) throw err;
var database = db.db("myFirstDatabase");
const cursor = database.collection(req.params.list_name).find({}); /* stuck here */
database.listCollections().toArray((err, collections) => {
if(err) throw err;
db.close();
collections.forEach(element => {
if(element.name == req.params.list_name){
current_list = element;
current_list_name = element.name;
}
});
task.find({}, (err, todo_tasks) => { /*currently using the model.find() method to list all the documents which always looks at the "tasks" collection*/
res.render("todo_list.ejs", { tasks: todo_tasks, lists: collections, curr_list: current_list_name });
});
});
});
});
我评论了我在上面的代码中遇到的问题。我正在尝试按名称获取 mongodb 集合,然后将其所有内容加载到列表中,但我不知道如何按名称查找集合。阅读 node.js 文档将我带到光标对象,它有大量的信息和属性,我不知道如何处理......
有没有一种简单的方法可以按名称查找集合并获取其文档列表?
编辑 1:
这是我添加任务的地方:
//ADD TASK TO LIST
app.post('/', async (req, res) => {
const tsk = new task({ /*the mongodb model for tasks*/
content: req.body.content,
deadline: req.body.deadline
});
try {
await tsk.save();
res.redirect("/");
} catch(e) {
console.log(e);
res.redirect("/");
}
});
【问题讨论】:
-
您的代码中有很多错误的地方(不是想烤什么的,我自己也去过那里,迷失在 JS 世界中)。如果您需要详细的答案(我稍后会发布),请在此处给我留言,如果没有,请尝试以下任何其他答案,看看它们是否适合您。
-
@GaëtanBoyals 无论如何,如果我的代码在第一个项目中表现良好,我会感到惊讶。我只是想学习。
-
我会认为这是肯定的。我会留下一个详细的答案来解决我在您的代码摘录中看到的内容。
-
非常感谢您,任何和所有信息都有帮助