简体   繁体   English

从 mongoDB 集合中获取数据到 ejs

[英]Get data from mongoDB collection to ejs

I was learning how to use MongoDB atlas.我正在学习如何使用 MongoDB 地图集。 I connected the database with my node app and I am also able to add data to it.我将数据库与我的节点应用程序连接起来,并且还可以向其中添加数据。 The only problem that I am facing is with ejs.我面临的唯一问题是 ejs。 I am not able to retrieve my filePath and title from my collection, even though I was able to log all of the data in my collection but I am stuck at how can I get title and filePath from my collection and use the data on my front-end.我无法从我的集合中检索我的文件路径和标题,即使我能够记录我的集合中的所有数据,但我被困在如何从我的集合中获取标题和文件路径并使用我前面的数据-结尾。 Here is my code:这是我的代码:

app.js:应用程序.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索引.ejs

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

You need to pass the variables you want to display to the res.render method:您需要将要显示的变量传递给res.render方法:

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

Renders a view and sends the rendered HTML string to the client.渲染视图并将渲染的 HTML 字符串发送到客户端。 Optional parameters:可选参数:

locals, an object whose properties define local variables for the view. locals,一个 object,其属性定义视图的局部变量。

callback, a callback function.回调,一个回调 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.发生错误时,该方法在内部调用 next(err)。

To make your code work, move the render function call inside the query callback, and pass the found users to it:要使您的代码正常工作,请将渲染 function 调用移动到查询回调中,并将找到的用户传递给它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM