Read the list of products in the database based on Nodejs and MongoDB
varHTTP = require ("http"), MONGO= Require ("MongoDB"), Events= Require ("Events"); Http.createserver (function(req, res) {varProducts_emitter =Newevents. Eventemitter (),//Create a link to the Northwind database. Equivalent to use Northwinddb =NewMongo. Db ("Northwind",NewMongo. Server (' localhost ', 27017, {}), {}); varListener =function(Products) {varHTML = [], Len =products.length; Html.push (' <! DOCTYPE html> '); Html.push (' ); Html.push (' ); Html.push (' <title>Nodejs</title> '); Html.push (' ); Html.push (' <body> '); if(Len > 0) {Html.push (' <ul> '); for(vari = 0; i < Len; i++) {Html.push (' <li> ' + products[i].name + ' </li> '); } Html.push (' </ul> '); } Html.push (' </body> '); Html.push (' ); Res.writehead ("Content-type:text/html"); Res.write (Html.join (‘‘)); Res.end (); Cleartimeout (timeout); } products_emitter.on (' Products ', listener); varTimeout = SetTimeout (function() {Products_emitter.emit (' Products ', []); Products_emitter.removelistener (' Products ', listener); }, 10000); Db.open (function() { //open a table named productsDb.collection ("Products",function(Err, collection) {//SELECT * FROM products equivalent to Db.products.find ()Collection.find (function(err, cursor) {Cursor.toarray (function(err, items) {Products_emitter.emit (' Products ', items); }); }); }); }); }). Listen (8000); Console.log ("Started");
On the Internet to find the above code [original], executed, visit http://127.0.0.1:8000/of course, there was nothing at first.
So the collection of products to the database Norhwind (collection) inserted two data, the shell command is as follows
> Use northwindswitched to db Northwind> db.products.insert ({' name ': ' Shanshan '})> Db.products.insert ({' name ': ' Sandy '})
Note that you do not need to create a collection beforehand, which is created automatically the first time you insert the data.
Refresh the page http://127.0.0.1:8000/again to see
Nodejs + MongoDB