首页 > 解决方案 > 使用 Mongoose .find() 在 EJS 模板中渲染数据

问题描述

我正在创建一个简单的 CRUD 应用程序。问题是:它连接到MongoDB就好了,我可以正常保存数据,也可以删除它。但是我好像找不到!我不知道错误是在 EJS 中还是在后端。

这是错误:

Lesson.forEach 不是函数

这是后端代码:

//search lessons
exports.searchLesson = (req, res) => {
    let searchField = req.body.searchField;
    if (req.query.id) {
        const id = req.query.id;

        Lesson.findById(id)
            .then(data => {
                if (!data) {
                    res.status(404).send({
                        message: 'User not found'
                    })
                } else {
                    res.send(data)
                }
            })
            .catch(err => {
                res.status(500).send({
                    message: 'Error retrieving lesson with id ' + id
                })
            });

    } else {
        Lesson.find({
                teacher: searchField
            })
            .then(lesson => {
                res.render('searchLesson.ejs', {
                    lessons: lesson
                })
            })
            .catch(err => {
                res.status(500).send({
                    message: err.message || "Error occured while retrieving lesson information"
                });
            });
    }
};

怎么了?

标签: node.jsmongodbexpressmongoose

解决方案


Gabriel Moura 一旦尝试lesson而不是lessons在前端这是类型错误,这意味着我们拼错了一些我们必须在控制器和 ejs 文件中更正的内容......


推荐阅读