javascript - 出现错误无法读取未定义的属性 'equals'

标签 javascript node.js mongodb express mongoose

我正在开发一个 CRUD 应用程序,该应用程序还允许使用 Cloudinary 包上传图像。我正在使用 Node.js、express 和 MongoDB。实现 Cloudinary 上传部分后,我的应用程序突然崩溃了。我不知道发生了什么事!我恢复了更改,但问题仍然存在。我收到错误

TypeError: C:\Users\Subhadeep\Documents\Web Jobs\SURJO\views\index.ejs:66
    64|             <td><%= student.author.center %></td>

    65|         </tr>

 >> 66|         <% }

    67|                             }); %>

    68| 

    69|         </tbody>


Cannot read property 'equals' of undefined

我的index.ejs文件粘贴在下面

<% include ./partials/header %>

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1>Students List</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="/">Home</a></li>
                        <li class="breadcrumb-item active">Students</li>
                    </ol>
                </div>
            </div>
        </div><!-- /.container-fluid -->
    </section>

    <!-- Main content -->
    <section class="content">
        <% if (error && error.length > 0 ) { %>
        <div class="alert alert-danger" role="alert">
            <%= error %>
        </div>
        <%}%>
        <% if (success && success.length > 0 ) { %>
        <div class="alert alert-info" role="alert">
            <%= success %>
        </div>
        <%}%>

        <div class="row">
            <div class="col-12">


                <div class="card">

                    <!-- /.card-header -->
                    <div class="card-body">
                        <table id="form" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>Date of Admission</th>
                                    <th>Name</th>
                                    <th>Date of Birth</th>
                                    <th>Caste</th>
                                    <th>Contact Number</th>
                                    <th>Registered Under</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Logic Will Go Here -->
                                <% students.forEach(function(student){
                                    if(student.author.id.equals(currentUser._id) || currentUser.isAdmin){ %>
        <tr>
            <td><%= student.created.toDateString() %></td>
            <td><a href="/students/<%= student._id %>"><%= student.name %></a></td>
            <td><%= student.dob %></td>
            <td><%= student.caste %></td>
            <td><%= student.phone %></td>
            <td><%= student.author.center %></td>
        </tr>
        <% } }); %>

        </tbody>
        <tfoot>
            <tr>
                <th>Date of Admission</th>
                <th>Name</th>
                <th>Date of Birth</th>
                <th>Caste</th>
                <th>Contact Number</th>
                <th>Registered Under</th>
            </tr>
        </tfoot>
        </table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<script>
    $(document).ready(function () {
        $('#form').DataTable({
            "order": [
                [0, "desc"]
            ]
        });
    });
</script>
<script>
    document.getElementById("viewAll").className += " active";
</script>
<!-- /.content-wrapper -->
<% include ./partials/footer %>

app.js 就在这里

// Required Routes
var express = require("express"),
    bodyParser = require("body-parser"),
    mongoose = require("mongoose"),
    ejs = require("ejs"),
    expressSanitizer = require("express-sanitizer"),
    Student = require("./models/students"),
    passport = require("passport"),
    localStrategy = require("passport-local"),
    User = require("./models/user"),
    flash = require("connect-flash"),
    methodOverride = require("method-override");
var app = express();


// Routers
var authRoute = require("./routes/authentication"),
    indexRoute = require("./routes/indexRoute");

//Server and Mongo and Other Setups
mongoose.connect("mongodb://localhost/surjo", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false
});
//App config
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(expressSanitizer());
app.use(methodOverride("_method"));
app.use(flash());
express.static("/uploads");


// PASSPORT Configuration
app.use(require("express-session")({
    secret: "Once there is something that is not found",
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// Routers Use

// Middleware
app.use(function (req, res, next) {
    res.locals.currentUser = req.user;
    res.locals.error = req.flash("error");
    res.locals.success = req.flash("success");
    next();
});
app.use(authRoute);
app.use(indexRoute);


//=====================================================
//Server Configuration for Node.js. Do not touch here!
// ====================================================
var port = process.env.PORT || 3000;
app.listen(port, function () {
    console.log("Server Has Started!");
});

app.get("/reg-new", function (req, res) {
    res.render("register-new");
})

这是索引路由文件:

var express = require("express"),
    router = express.Router({
        mergeParams: true
    });
var Student = require("../models/students");
var User = require("../models/user");
var middleware = require("../middleware");

//RESTful Routes

// Index Route
router.get("/", middleware.isLoggedIn, function (req, res) {
    res.redirect("/students");
})

// View All Students
router.get("/students", middleware.isLoggedIn, function (req, res) {
    Student.find({}, function (err, students) {
        if (err) {
            req.flash("error", "Sorry! Something went wrong!");
            console.log(err);
        } else {
            res.render("index", {
                students: students,
                currentUser: req.user,
            });
        }
    });
});

//NEW Route
router.get("/students/new", middleware.isLoggedIn, function (req, res) {

    res.render("new");
})

// CREATE Route
router.post("/students", middleware.isLoggedIn, function (req, res) {
    req.body.student.body = req.sanitize(req.body.student.body);
    Student.create(req.body.student, function (err, newStudent) {
        if (err) {
            res.render("/new");
        } else {
            newStudent.author.id = req.user._id;
            newStudent.author.username = req.user.username;
            newStudent.author.center = req.user.center;
            newStudent.save();
            res.redirect("/students");
        }
    });
});


//SHOW Route
router.get("/students/:id", middleware.isLoggedIn, function (req, res) {
    Student.findById(req.params.id, function (err, foundStudent) {
        if (err) {
            req.flash("error", "Sorry! Something Went Wrong!")
            res.redirect("/students");
        } else {
            if (foundStudent.author.id.equals(req.user._id) || req.user.isAdmin) {
                res.render("show", {
                    student: foundStudent
                });
            } else {
                req.flash("error", "You are not authorized to view.");
                res.redirect("/students");
            }
        }
    });
});


//EDIT Route
router.get("/students/:id/edit", middleware.checkStudentOwnership, function (req, res) {
    // is user logged in
    Student.findById(req.params.id, function (err, foundStudent) {
        if (foundStudent.author.id.equals(req.user._id)) {
            res.render("edit", {
                student: foundStudent
            });
        } else {
            res.render("/students/:id", {
                error: "You are not authorised."
            });
        }
    });
});

// UPDATE Route
router.put("/students/:id", middleware.isLoggedIn, function (req, res) {
    req.body.student.body = req.sanitize(req.body.student.body);
    Student.findByIdAndUpdate(req.params.id, req.body.student, function (err, foundStudent) {
        if (foundStudent.author.id.equals(req.user._id)) {
            res.redirect("/students/" + req.params.id);
        } else {

            res.redirect("/index");
        }
    });
});

//DESTROY Route
router.delete("/students/:id", middleware.checkStudentOwnership, function (req, res) {
    Student.findByIdAndRemove(req.params.id, function (err) {
        if (err) {
            res.redirect("/index");
        } else {
            req.flash("success", "Student Deleted.");
            res.redirect("/students/");
        }
    })
})

router.get("/login", function (req, res) {
    res.render("login");
})

// Export
module.exports = router;

我已经花了近24小时解决这个问题,但仍然无法解决!希望能在这里得到解决方案。谢谢!

最佳答案

下次我建议在谷歌上搜索javascript Cannot read property of undefined(基本上是你得到的错误,但没有变量名称)。我怀疑 Stack Overflow 上的许多人会认为这是一个低质量的问题。

现在,一个明确的答案:

Cannot read property 'equals' of undefined 表示 Javascript 解释器正在尝试访问 undefined variable 内的属性 equals

Typerror bla ba index.ejs:66 表示从 Javascript 的 Angular 来看,错误发生在第 66 行。在你的例子中,看起来 ejs 的东西有点搞乱了行号,但是如果你调查一下,你会发现你在第 56 行调用 student.author.id.equals 。如果如果您对此进行调试,您会发现 student.author.id 可能由于各种原因之一而未定义

关于javascript - 出现错误无法读取未定义的属性 'equals',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143558/

相关文章:

javascript - 在 Javascript 中使用 document.domain 的同源策略解决方法

php - 追溯记录+评论的策略

node.js - 使用 nave 和 Node.js 的 NPM 基础知识

mongodb - 匹配数组中的多个值

mongodb - 如何定义复合哈希 mongodb 索引?

javascript - jslint 停在 $(document).ready 行

javascript - GA——Javascript Array Auto 的 onClick with Name in Alpha

javascript - 为什么我得到这个 'res.render() is not a function'

javascript - node.js:包括外部 grunt 配置

mongodb - 如何在 Mongodb、Go 中向数组添加更多字段?