创建一个具有Web应用程序的练习,该应用程序让用户输入其投票者ID并选择一个区号。然后,它显示了所有全州和地方选举比赛。全州范围内的区号为0,而本地人列出的特定区号为1到6。使用.find函数时,它仅适用于本地和全州范围,但是当使用$ or两者时,我得到一个“解析”错误:第55行出现意外的令牌:”。我安装了mongo,monogodb,mongoose,jquery,express,express-handlebars和body解析器。
const express = require('express');
let app = express();
let bodyParser = require('body-parser');
app.use( bodyParser.urlencoded( {extended: false} ) );
// Mongoose options
const options = { server: {socketOptions: {keepAlive: 1} } };
// Set up first mongoose connection
let mongoose1 = require('mongoose');
let db1 = mongoose1.createConnection('mongodb://ballotRO:XooRqtLAxe9ZKK@ds143953.mlab.com:43953/project5', options);
let Race = require('./models/race.js')(db1);
// Set up second mongoose connection
let mongoose2 = require('mongoose');
let db2 = mongoose2.createConnection('mongodb://disuser:RqCRfwUck5B7jYV@ds121192.mlab.com:21192/project5-results', options);
let Vote = require('./models/vote.js')(db2);
// Open the connections
db1.on('error', console.error.bind(console, 'connection error:'));
db1.once('open', function() { console.log("db1 connected"); });
db2.on('error', console.error.bind(console, 'connection error:'));
db2.once('open', function() { console.log("db2 connected"); });
// set up handlebars view engine
let handlebars = require('express-handlebars')
.create({ defaultLayout:'main' });
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('port', process.env.PORT || 3000);
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('home');
});
// Get the appliacable races and then render the ballot
// expects a form submission witha district and voterId
app.post('/ballot', function(req, res) {
// Make sure the form contains a district and a voter id
if(req.body && req.body.district && req.body.voterId) {
const districtInt = parseInt(req.body.district);
Race.find($or : [{districts: 0}, {districts: districtInt}]).then(function(races) {
res.render("ballot", {
voterId: req.body.voterId,
district: districtInt,
races: races,
});
}).catch(function(err) {
console.log(err);
res.redirect("/");
});
} else {
res.redirect("/");
}
});
app.post("/vote", function(req, res) {
if(req.body.voterId) {
console.log(req.body);
const votes = Object.assign({}, req.body);
delete votes.voterId;
delete votes.disctrict;
new Vote({
voterid: req.body.voterId,
district: req.body.district,
votes: votes
}).save().then(function(savedVote) {
});
res.redirect("/");
}
});
// 404 catch-all handler (middleware)
app.use(function(req, res, next){
res.status(404);
res.render('404');
});
// 500 error handler (middleware)
app.use(function(err, req, res, next){
console.error(err.stack);
res.status(500);
res.render('500');
});
app.listen(app.get('port'), function(){
console.log( 'Express started on http://localhost:' +
app.get('port') + '; press Ctrl-C to terminate.' );
});