Skip to content

Instantly share code, notes, and snippets.

Created June 21, 2015 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/6eccd6ae961ebf1bd7aa to your computer and use it in GitHub Desktop.
Save anonymous/6eccd6ae961ebf1bd7aa to your computer and use it in GitHub Desktop.
// An Introduction To Node.js And MongoDB
// By Elliot Bonneville
// May 22nd, 2014
// http://www.smashingmagazine.com/2014/05/22/detailed-introduction-nodejs-mongodb/
var http = require("http"),
mongojs = require("mongojs");
// NOTE from the transcriber: The original tutorial assigned variable db to the
// execution of mongojs.connect(), however as of today (2015-06-21) it appears
// the correct call is simply mongojs(). I'm completely new to this, though,
// I could be wrong, but mongojs.connect() did not work for me. I found this
// other approach here:
//
// http://blog.nodejitsu.com/npmawesome-mongojs-a-driver-to-closer-match-mongodb-api/
var uri = "mongodb://demo_user:demo_password@ds027769.mongolab.com:27769/demo_database",
db = mongojs(uri, ["demo_collection"]);
var server = http.createServer(requestHandler);
function requestHandler(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
db.demo_collection.find(
{"color": "red"},
function(err, records) {
if (err) {
console.log("There was an error executing the database query.");
response.end();
return;
}
// NOTE from the transcriber: I replaced paragraphs with list-items
// because I'm a jerk. Hey, you're looking at my actual
// walk-through of this tutorial. Everyone likes to customize
// their tutorial results, right?
var html = "<h2>Vehicles with a red finish</h2>\n<ol>\n",
i = records.length;
while (i--) {
html += "<li><b>Name:</b> "
+ records[i].name
+ " <br/><b>Number of wheels:</b> "
+ records[i].wheels
+ " <br/><b>Color:</b> "
+ records[i].color
+ "</li>\n";
}
html += "</ol>\n";
// NOTE from the transcriber: I wanted to see everything that had
// had been returned, so I employed JSON.stringify to visualize
// the records array in a preformatted text block.
html += "<pre>";
html += JSON.stringify(records, null, "\t");
html += "</pre>";
response.write(html);
response.end();
}
);
}
server.listen(8888);
console.log("Server listening on port 8888.");
@annessca
Copy link

annessca commented Sep 6, 2017

Thanks a lot for making it work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment