从 mongoDB 集合中获取数据到 ejs

时间:2021-02-18 19:48:17

标签: node.js mongodb express mongoose ejs

我正在学习如何使用 MongoDB 图集。我将数据库与我的节点应用程序连接起来,我还可以向其中添加数据。我面临的唯一问题是 ejs。我无法从我的收藏中检索我的 filePath 和标题,即使我能够记录我收藏中的所有数据,但我仍然不知道如何从我的收藏中获取标题和 filePath 并使用我前面的数据-结尾。这是我的代码:

app.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");
});

index.ejs

<% newListItems.forEach(function(item){ %>
       <div class="video-div">
          <p><%=item.title%></p>
       </div>
<% }) %>

1 个答案:

答案 0 :(得分:1)

您需要将要显示的变量传递给 res.render 方法:

<块引用>

res.render(view [, locals] [, callback])

渲染一个视图并将渲染的 HTML 字符串发送到客户端。可选参数:

locals,一个对象,其属性定义了视图的局部变量。

callback,一个回调函数。如果提供,该方法将返回可能的错误和呈现的字符串,但不执行自动响应。发生错误时,该方法会在内部调用 next(err)。

要使您的代码工作,请在查询回调中移动渲染函数调用,并将找到的用户传递给它:

app.get("/", function (req, res) {
  User.find({}, function (err, foundItems) {
    console.log(foundItems.title);
    
    res.render("index", {newListItems: foundItems});
  });
});