-
Notifications
You must be signed in to change notification settings - Fork 30
Home
amark edited this page Jun 14, 2011
·
3 revisions
Welcome to the mongous wiki! Please make this as resourceful as possible for people!
alangrus has provided the following example of mongous for node v0.4.8:
============== node_mongous.js file contents ===========================
// Alan Gruskoff, [email protected], May 2011
// Forming a web service listener via node for the mongous driver
//
// At a command line start the web server as: node node_mongous.js
//
// then, use this for your URL: http://127.0.0.1:8124/?database=<your database>&collection=<your collection>
// the doResponse function will parse the inbound request URL and dump the contents
// of each field of <your collection>, sending those contents to the console and
// back to the web page that called it.
//-------------------------------------------------------------------------------//
// node utilities
Url = require("url");
Http = require("http");
// load mongous driver, adjust the path to mongous as needed.
var db = require('mongous').Mongous;
// get ready for ajax
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
function doResponse( request, response ) {
var theQuery = Url.parse(request.url, true);
var qStuff = "";
var qArray = theQuery.query;
// The find syntax is expecting an object of fields to display
var field_list = {};
// the (i) value is the index of the array's keys, can be a string
for (var i in qArray) {
qStuff += i + '=' + qArray[i] + " ";
}
var database = qArray.database;
if ( database == null ) { database = 'test'; }
var collection_id = qArray.collection;
console.log('Server received request: ' + request.method + ' ' + qStuff + ' ' + theQuery.pathname);
db(database + "." + collection_id).find({}, {}, function(reply){
// resultText holds the text of the reply content
var resultText = "";
// reply.documents is a JSON object we will now loop through to parse
for (var idx in reply.documents) {
resultText += "\nmongo doc " + idx + ") ";
var curObj = reply.documents[idx];
for (var i in curObj) {
line = curObj[i];
// with this driver, _id returns a binary object that needs to be parsed.
line = JSON.stringify( curObj[i] );
resultText += i + " = " + line + "\n";
}
}
console.log("MongoDB reply=" + resultText);
// HTTP Header is optional
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write( resultText );
response.end();
});
}
Http.createServer(function (request, response) {
doResponse( request, response );
}).listen(8124);
console.log('node mongous Server running at http://127.0.0.1:8124/');
=======================================================================