我试图将我的MongoDB数据注入HTML,但我一直这样做: "错误:每个都不匹配其他",我试图更改几行,但我仍然收到此错误,它是我的第一个使用MongoDB或数据库的项目。 为了使我的代码工作,我需要更改什么?是HTML还是节点问题?
HTML
{{#each ideas}}
<div>
<p>{{tip}}</p>
</div>
{{/else}}
server.js
const path = require('path');
const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const handlebars = require('handlebars')
const app = express();
//map global promise - get rid of warning
mongoose.Promise = global.Promise;
// connect to mongoose
mongoose.connect('mongodb://localhost/peppino-calc', {
useMongoClient: true
})
.then(() => { console.log('MongoDB connected...')})
.catch(err => console.log(err));
//Load salaryModel
require('./modles/Idea.js');
const Idea = mongoose.model('ideas');
//handlebars middleware
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
handlebars.registerHelper("toLowerCase", function(input) {
var output = input.toLowerCase();
return output.replace(" ", "");
});
//body parser middleware
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
// post history page
app.get('/history', (req, res) => {
Idea.find({})
.sort({date: 'desc'})
.then(ideas => {
res.render('../js/newJs/history', {
ideas:ideas
})
});
})
//process form
app.post('/ideas', (req, res) => {
let errors = [];
if(errors.length > 0) {
console.log(errors[0]);
} else {
const newUser = {
amount: req.body.totalamount,
hours: req.body.totalhours,
salary: req.body.totalsalary,
tip: req.body.totaltip,
date: req.body.datetotal
}
new Idea(newUser)
.save()
.then(idea => {
res.redirect('/history');
})
}
});
app.use(express.static(path.join(__dirname, './js/newJs')));
app.set('port', process.env.PORT || 5700);
var server = app.listen(app.get('port'), function() {
console.log('listening on port ', server.address().port);
});
答案 0 :(得分:1)
错误来自Handlebars,应使用#each
关闭/each
迭代器
{{#each ideas}}
<div>
<p>{{tip}}</p>
</div>
{{/each}}
else
可用于有空列表的情况,如果它在each
部分内:
{{#each ideas}}
<div>
<p>{{tip}}</p>
</div>
{{else}}
<div>
<p>none</p>
</div>
{{/each}}
答案 1 :(得分:1)
我知道您现在应该已经解决了这个问题,但是我只想为将来可能会遇到此类错误的人回答这个问题。
查看您的代码,该错误位于您的HTML文件(Handlebars语法)中,而不是server.js。
您的{{#each}}
迭代器应以{{/each}}
而不是{{/else}}
结束。
所以您的代码应如下所示:
{{#each ideas}}
<div>
<p>{{tip}}</p>
</div>
{{else}}
<div>
<p>Do nothing</p>
</div>
{{/each}}