仅在客户端显示标题 returns 未定义

Displaying only the title on the client returns undefined

我在 mongoosejs 中定义了一个模式,如下所示:

var uploadSchema = mongoose.Schema({
    title            : String,
    happy            : String,
});

我希望我的数据库中的数据显示在客户端上(我正在使用 ejs 进行模板化):

app.get('/yay', function (req, res, next){
        Upload.find({}, function (err, course){
            res.render('./pages/yay.ejs', {course: course});
        });
    });

在客户端显示:

<div class="well">
    <p><%= course %></p>
</div> 

但这只显示了 ID 为 whatWillLearn 的整个数据库。我只需要显示标题。我怎样才能做到这一点?我试过这个:

app.get('/yay', function (req, res, next){
            Upload.find({}, function (err, course){
                res.render('./pages/yay.ejs', {course: course.title});
            });
        });

但它只是 returns 在客户端未定义。我该怎么办?

看起来您正在 return 创建一个数组,但是传递给渲染的对象中没有设置正确的变量

试一试(这应该是数组中的第一个课程):

app.get('/yay', function (req, res, next){
  Upload.find({}, function (err, courses) {
    res.render('./pages/yay.ejs', { happy: courses[0].title });
  });
});

如果您没有课程,这将不起作用。您可能应该遍历 return 的所有课程并将其打印出来,或者将 change Upload.find 更改为 Upload.findOne 以从 DB

中取回 1