问题是我有打字错误,或者我现在无法发现一个错误。一切都应该正常工作(因为我将那部分代码复制到了我的代码中),但结果如下:
TypeError: C:\Users\USER\Realtime-Chat\playground-login\views\index.pug:3
1| extends layout
2| block content
> 3| if registrations.length
4| table
5| tr
6| th Name
Cannot read property 'length' of undefined
[...]
at router.get (C:\Users\USER\Realtime-Chat\playground-login\routes\index.js:33:7)
[...]
上面提到的代码行正好是:
32> Registration.find()
我找不到适合我情况的解决方案...首先,我寻找了typeos的可能方案(因为注册是很难键入的单词)。然后什么也没发现。后来,我将每一步记录到控制台,以逐步了解发生了什么。除了index.js文件中的三行(NR1&NR2记录req.body,而NR3记录req.body和Registration集合(带有对象id的req.body),这一切都没发现,我找不到原因)。然后我再次检查了index.pug,Registration.js和index.js,但是它仍然返回undefined。然后我认为它可能已被弃用,但我不知道已弃用了什么。我做的最后一件事是检查你们中的任何一个是否有相同或相似的问题,但是找不到匹配项...
//模型目录中的Registration.js文件:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const registrationSchema = new Schema({
//[...]
});
module.exports = mongoose.model('Registration', registrationSchema);
路径目录中的// index.js文件:
//[...]
const Registration = require('../models/Registration');
//[...]
router.post('/', [{...}], (req, res) => {
//NR1
const errors = validationResult(req);
if(errors.isEmpty()) {
//NR2
const registration = new Registration(req.body);
registration.save()
.then(() => {res.send('Thanks for your registration!')})
.catch(() => {res.send('Sorry! Something went wrong.')})
} else {
res.render('form', {
title: 'Registration form',
errors: errors.array(),
data: req.body
});
//NR3
};
});
router.get('/registrations', (req, res) => {
Registration.find()
.then((registrations) => {
res.render('index', {title: 'Listing registrations', registrations})})
.catch(() => {res.send('Sorry! Something went wrong.')});
})
//[...]
视图目录中的// index.pug文件:
extends layout
block content
if registrations
table
tr
th Name
th Email
each registration in registrations
tr
td= registrations.name
td= registrations.email
else
p No registrations yet :(
它应该在路由/ registrations中返回带有键名称和电子邮件的html表