I am trying to read from MongoDB and print the contents to a webpage. I am using mongodb module to read from Mongo.
I am able to successfully read and print the data to a webpage but I am not able to figure out when to close the db and when to end the http connection. Hence my webpage prints results but keeps waiting for the server to send something.
I referred the following questions but can't understand what I need to do in this specific scenario:
- Looking for help with reading from MongoDB in Node.JS
- When to close MongoDB database connection in Nodejs
- How to close all connections to the MongoDB server
Here is my code:
/* Opens the secondary collection and goes through each entry*/
var getClientIDs = function(collect, res) {
db.collection(collect, function(err, collection) {
var cursor = collection.find();
cursor.each(function(err, item) {
if(item != null) {
console.log(item['_id'] +"\t" + item['name']);
res.write(item['_id'].toString());
res.write("  ");
res.write(item['name'].toString());
res.write("</br>");
}
/*else {
res.end("The End");
db.close();
} Closes connection before other stuff is done. */
});
});
}
/* Opens the main collection and goes through each entry*/
var openCollection = function(collect, res) {
console.log(green);
// Establish connection to db
db.open(function(err, db) {
// Open a collection
db.collection(collect, function(err, collection) {
// Create a cursor
var cursor = collection.find();
// Execute the each command, triggers for each document
cursor.each(function(err, item) {
if(item != null) {
getClientIDs(item['_id'], res);
}
/* else {
db.close();
} This closes the connection before other stuff is done */
});
});
});
}
/* Start Here */
var http = require('http');
var port = 8888;
http.createServer(function (req, res) {
res.writeHead(200,{"Content-Type": "text/html; charset=utf-8"});
openCollection('company',res);
}).listen(port);
The way the db is that there is a collection called 'company' and it has a bunch of IDs in it. There are other collections with the name of the id :
company = {{ _id: 'A001' }
{ _id: 'A002' }
{ _id: 'A003' }
}
A001 = {{_id: "A001-01", "name":"foo"}
{_id: "A001-02", "name":"bar"}}
A002 = {{_id: "A002-01", "name":"foo2"}
{_id: "A002-02", "name":"bar2"}}
I did not create the collections this way. This was what I had to work with and create a script which would just print IDs and names on a webpage.
With my code, the webpage prints:
A001-01 foo
A001-02 bar
A002-01 foo2
A002-02 bar2
Thank you.