-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
157 lines (133 loc) · 5.81 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
//
// Floccus: Tournament Manager
//
// Preamble
var http = require ('http'); // For serving a basic web page.
// call the packages we need
var express = require('express');
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var app = express(); // create our app w/ express
var morgan = require('morgan'); // log requests to the console (express4)
var mongoose = require ("mongoose"); // The reason for this demo.
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var database = require('./config/database'); // load the database config
// Here we find an appropriate database to connect to, defaulting to
// localhost if we don't find one.
var uristring = database.url;
// The http server will listen to an appropriate port, or default to
// port 5000.
var theport = process.env.PORT || 5000;
// Makes connection asynchronously. Mongoose will queue up database
// operations and release them when the connection is complete.
mongoose.connect(uristring, function (err, res) {
if (err) {
console.log ('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log ('Succeeded connected to: ' + uristring);
}
});
app.configure(function() {
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());
});
// routes ======================================================================
require('./app/routes.js')(app);
// listen (start app with node server.js) ======================================
app.listen(theport);
console.log("App listening on port 8080");
// This is the schema. Note the types, validation and trim
// statements. They enforce useful constraints on the data.
var userSchema = new mongoose.Schema({
name: {
first: String,
last: { type: String, trim: true }
},
age: { type: Number, min: 0}
});
// Compiles the schema into a model, opening (or creating, if
// nonexistent) the 'PowerUsers' collection in the MongoDB database
var PUser = mongoose.model('PowerUsers', userSchema);
// Clear out old data
PUser.remove({}, function(err) {
if (err) {
console.log ('error deleting old data.');
}
});
// Creating one user.
var johndoe = new PUser ({
name: { first: 'John', last: ' Doe ' },
age: 25
});
// Saving it to the database.
johndoe.save(function (err) {if (err) console.log ('Error on save!')});
// Creating more users manually
var janedoe = new PUser ({
name: { first: 'Jane', last: 'Doe' },
age: 65
});
janedoe.save(function (err) {if (err) console.log ('Error on save!')});
// Creating more users manually
var alicesmith = new PUser ({
name: { first: 'Alice', last: 'Smith' },
age: 45
});
alicesmith.save(function (err) {if (err) console.log ('Error on save!')});
// In case the browser connects before the database is connected, the
// user will see this message.
var found = ['DB Connection not yet established. Try again later. Check the console output for error messages if this persists.'];
// Create a rudimentary http server. (Note, a real web application
// would use a complete web framework and router like express.js).
// This is effectively the main interaction loop for the application.
// As new http requests arrive, the callback function gets invoked.
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
createWebpage(req, res);
}).listen(theport);
function createWebpage (req, res) {
// Let's find all the documents
PUser.find({}).exec(function(err, result) {
if (!err) {
res.write(html1 + JSON.stringify(result, undefined, 2) + html2 + result.length + html3);
// Let's see if there are any senior citizens (older than 64) with the last name Doe using the query constructor
var query = PUser.find({'name.last': 'Doe'}); // (ok in this example, it's all entries)
query.where('age').gt(64);
query.exec(function(err, result) {
if (!err) {
res.end(html4 + JSON.stringify(result, undefined, 2) + html5 + result.length + html6);
} else {
res.end('Error in second query. ' + err)
}
});
} else {
res.end('Error in first query. ' + err)
};
});
}
// Tell the console we're getting ready.
// The listener in http.createServer should still be active after these messages are emitted.
console.log('http server will be listening on port %d', theport);
console.log('CTRL+C to exit');
//
// House keeping.
//
// The rudimentary HTML content in three pieces.
var html1 = '<title> hello-mongoose: MongoLab MongoDB Mongoose Node.js Demo on Heroku </title> \
<head> \
<style> body {color: #394a5f; font-family: sans-serif} </style> \
</head> \
<body> \
<h1> hello-mongoose: MongoLab MongoDB Mongoose Node.js Demo on Heroku </h1> \
See the <a href="https://devcenter.heroku.com/articles/nodejs-mongoose">supporting article on the Dev Center</a> to learn more about data modeling with Mongoose. \
<br\> \
<br\> \
<br\> <h2> All Documents in MonogoDB database </h2> <pre><code> ';
var html2 = '</code></pre> <br\> <i>';
var html3 = ' documents. </i> <br\> <br\>';
var html4 = '<h2> Queried (name.last = "Doe", age >64) Documents in MonogoDB database </h2> <pre><code> ';
var html5 = '</code></pre> <br\> <i>';
var html6 = ' documents. </i> <br\> <br\> \
<br\> <br\> <center><i> Demo code available at <a href="http://github.com/mongolab/hello-mongoose">github.com</a> </i></center>';