node.js - 从 mongoDB 集合中获取数据到 ejs
问题描述
我正在学习如何使用 MongoDB 地图集。我将数据库与我的节点应用程序连接起来,并且还可以向其中添加数据。我面临的唯一问题是 ejs。我无法从我的集合中检索我的文件路径和标题,即使我能够记录我的集合中的所有数据,但我被困在如何从我的集合中获取标题和文件路径并使用我前面的数据-结尾。这是我的代码:
应用程序.js:
mongoose.connect(
"mongodb+srv://<name>:<password>t@cluster0.cqqda.mongodb.net/proDB?retryWrites=true&w=majority"
);
const connectionParams = {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
};
mongoose.set("useCreateIndex", true);
const dbName = "proDB";
const userSchema = new mongoose.Schema({
title: String,
filepath: String,
});
userSchema.plugin(findOrCreate);
const User = new mongoose.model("User", userSchema);
app.get("/", function (req, res) {
User.find({}, function (err, foundItems) {
console.log(foundItems.title);
});
res.render("index");
});
app.post("/upload", function (req, res, err) {
const user = User({
title: req.body.podcastTitle,
filepath: req.body.filePath,
});
user.save();
res.redirect("/admin-login");
});
索引.ejs
<% newListItems.forEach(function(item){ %>
<div class="video-div">
<p><%=item.title%></p>
</div>
<% }) %>
解决方案
您需要将要显示的变量传递给res.render
方法:
res.render(view [, locals] [, callback])
呈现视图并将呈现的 HTML 字符串发送到客户端。可选参数:
locals,一个对象,其属性定义视图的局部变量。
回调,回调函数。如果提供,该方法将返回可能的错误和呈现的字符串,但不执行自动响应。发生错误时,该方法在内部调用 next(err)。
要使您的代码正常工作,请在查询回调中移动渲染函数调用,并将找到的用户传递给它:
app.get("/", function (req, res) {
User.find({}, function (err, foundItems) {
console.log(foundItems.title);
res.render("index", {newListItems: foundItems});
});
});
推荐阅读
- c# - 在 NAudio 中使用断言
- javascript - 如何为一个元素设置更改属性?使用 JS 而不是 JQuery
- selenium - “org.openqa.selenium.WebDriverException:java.net.SocketException:软件导致连接中止:recv 失败”尝试启动 Firefox
- java - 流 - 过滤所有不抛出异常
- maven - 部署到 Heroku 时自定义 Maven 命令
- python - 将生成的 csv 文件分配给 django 模型
- python - .split() 是否始终保留字符串中元素的顺序?
- ios - SDWebImage 正在部分加载,即使在终止应用程序后也没有加载回来
- matplotlib - 在 imshow 中绘图未正确采用 x 值
- webpack - WEBPACK 4 SplitChunksPlugin 不拆分