尝试使用mongoose、express和ejs将数据从mongodb显示为html

lyr7nygr  于 2023-03-17  发布在  Go
关注(0)|答案(1)|浏览(155)

到目前为止,我可以让它将“测试”字符串打印到我的HTML页面。但是,我不能让它打印数据库中的数据,而且它没有抛出任何类型的错误。
我试着让它列出数据库中的数据到HTML页面,看看我是从DB中拉出要显示的信息。实际的结果是我可以看到我的“测试”打印,但这是我在网页上看到的全部。
index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial 
scale=1.0">
<title>Document</title>
</head>
<body>
    <%clinicsList.forEach(function(clinic){ %>
        <p><%= clinic.name %></p>
    <%})%>
        <h1><%= userName %></h1>
</body>
</html>

server.js

const express = require("express");
const mongoose = require("mongoose");
const ejs = require("ejs");
const app = express();

app.set("view engine", "ejs");

mongoose.connect("");

const clinicSchema = {
    name: String,
    directions: String,
    telephone: String,
    website: String,
    address: String,
}

const Clinic = mongoose.model("Clinic", clinicSchema);

app.get("/", function (req, res) {
    Clinic.find({}, function(err, clinicsList) {
        res.render("index", {
                clinicsList: data,
                userName: "Test"
        })
    })
})

app.listen(8080, function() {
    console.log("Server is running on port 8080");
})
6jygbczu

6jygbczu1#

render参数更改为:

app.get('/', function async (req, res) {
  try {
    const clinicsList = await Clinic.find({});
    res.render('index', {
      clinicsList,
      userName: 'Test',
    });
  } catch (err) {
    res.send('Something went wrong');
  }
});

此外,在EJS中添加一个检查,以检测在呈现clinicsList之前是否已经定义了它:

<%if (clinicsList) { %>
    <%clinicsList.forEach(function(clinic){ %>
        <p><%= clinic.name %></p>
    <%})%>
<% } else { %>
    <p>Loading...</p>
<% } %>

相关问题