-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
72 lines (55 loc) · 1.64 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var express = require('express');
var app = express();
//Mongoose and connection to MongoDB
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
//setting up schemas and models
var Schema = mongoose.Schema;
var VoteSchema = new Schema({
email: {type: "String"},
idea: {type: "Number"}
});
try {
var Vote = mongoose.model('Vote', VoteSchema, 'Votes');
}
catch(error) {}
app.set('port', (process.env.PORT || 8080))
app.use(express.static(__dirname + '/views'));
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.render("index.ejs");
});
app.get('/projectphl', function(req, res) {
res.render('projectphl.ejs');
});
app.post('/vote', function(req, res) {
var email = req.body.email;
var ideas = req.body.ideas;
//if email is found, it will be passed into the callback function's "entry" parameter.
Vote.findOne({ 'email': email }, function(err1, entry) {
if(err1) {
res.send(500, {error: "There was an error during the database lookup."});
}
//if entry is null, add the vote.
if(entry == null) {
for (var i = 0; i < ideas.length; i++) {
var vote = new Vote({email: email, idea: ideas[i]});
vote.save(function(err2, data) {
if(err2) {
console.log("There was an error: " + err);
res.send(500, {error: "There was an error saving the vote, please try again."});
}
else {
res.send(200);
}
});
}
}
//otherwise, send back a bad request. Do not save anything to the db.
else {
res.send(500, {error: "Voter has already voted.", emailUsed: true});
}
});
});
app.listen(app.get('port'));