首页 > 解决方案 > 从 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>
<% }) %>

标签: node.jsmongodbexpressmongooseejs

解决方案


您需要将要显示的变量传递给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});
  });
});

推荐阅读