mongoose 引用错误:“未定义明细,EJS”

kgsdhlau  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(114)

我不知道为什么这个错误不断发生我已经在细节中声明了值,但它仍然不断给我错误“details not define”,这段代码的目的是从mongodb指南针数据库中获取数据并显示它.但当我打开页面时,它给我这个错误.我是一个初学者,所以请让它去任何问题的问题,我已经尽了最大的努力来解决它,但无法做到这一点。

获取.js

var express = require("express"),
    app = express(),
    bodyparser = require("body-parser"),
    mongoose = require("mongoose");
mongoose.connect("mongodb+srv://mangement:killerloui@cluster0.qffmthl.mongodb.net/newcollection", {
    useNewUrlParser: true
});
app.use(bodyparser.urlencoded({
    extended: true
}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/public'));
app.get("/index", function(req, res) {
    res.render("index");
});
const contactSchema = new mongoose.Schema({
    name: String,
    salary: String,
    idno: String,
    gender: String,
    date: String,
});
const Contact = mongoose.model("Contact", contactSchema);
app.get("/", function(req, res) {
    res.render("index", {
        details: null
    })
})
app.get("/getdetails", function(req, res) {
    Contact.find({}, function(err, allDetails) {
        if (err) {
            console.log(err);
        } else {
            res.render("index", {
                details: allDetails
            })
        }
    })
})
app.listen(3000, "localhost", function() {
    console.log("server has started");
})

索引.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>
<style>
    #heading{
        margin-left: 39%;
    }
    table {
    margin-left: 29%;
    align-items: center;
    border: 2px solid;
}
th{
    border: 2px solid black;
}
td{
    border: 2px solid black;
}

</style>
<body>
    <div>
        <a href="/getdetails">Get Details</a>
        </div>
        <hr>
        
        <% if(details!=null) { %>
        <h2 id="heading">REGISTER RECORDS</h2>
        <table >
        <tr>
            <th id="n1">Name</th>
            <th id="n2">Salary </th>
            <th id="n3">ID-NO</th>
            <th id="n4">Gender</th>
            <th id="n5">DATE JOIN</th>
          
        </tr>
        <% details.forEach(function(item){ %>
        <tr id="fix" >
            <td><%= item.name%></td>
            <td><%= item.salary %></td>
            <td><%= item.idno%></td>
            <td><%= item.gender%></td>
            <td ><%= item.date%></td>
            
        
        </tr>
        <% }) %>
        </table>
        <% } %>
       
        
</body>
</html>
hec6srdp

hec6srdp1#

更改此行:

<% if(details!=null) { %>

对此:

<% if( typeof(details) =="undefined") { %>

问题是,您的details!=null行查找details的值,但您从未在ejs文件中声明过它。typeof是检查是否声明过值并查看其值的好方法。

相关问题