从mongoDBcollection获取数据到ejs

Get data from mongoDB collection to ejs

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

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>
<% }) %>

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

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

Renders a view and sends the rendered HTML string to the client. Optional parameters:

locals, an object whose properties define local variables for the view.

callback, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes next(err) internally.

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

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