-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
60 lines (53 loc) · 1.66 KB
/
server.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
var http = require("http"),
mongodb = require("mongodb");
var mongoServer = new mongodb.Server("ds035747-a.mongolab.com", 35747, {
auto_reconnect: true,
socketOptions: { keepAlive: 300 }
}),
dbConnector = new mongodb.Db("testauth", mongoServer, {});
mongoServer.on("error", function(err){
console.log("error in server:", server);
});
console.log("connecting");
dbConnector.open(function(err, db){
if(err){
return console.log(err);
}
console.log("authenticating");
db.authenticate("testuser", "testpass", function(err){
if(err){
return console.log(err);
}
db.on("close", function(){
console.log("connection was closed," +
"but the driver should reconnect because we used auto_reconnect");
});
db.on("error", function(err){
console.log("error in db:", err);
});
console.log("inserting sample data");
db.collection("test").insert([
{foo: 1, bar: 2},
{foo: 1, bar: 2}
], function(err, results){
startHttpServer(db);
});
});
});
function startHttpServer(db){
console.log("starting web server");
http.createServer(function(request, response){
db.collection("test").find({}).toArray(function(err, results){
response.writeHead(200, {'Content-Type': 'text/plain'});
if(!err){
response.end(JSON.stringify(results, null , 2));
}else{
response.write("message: " + err.message + "\n\n");
response.write("stack: " + err.stack + "\n\n");
response.end();
}
});
}).listen(process.env.port || 8989, function(){
console.log("running in http://localhost:" + (process.env.port || 8989).toString());
});
}