Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How do I capture a MongoDB query as a string and display it in my Node JS page (using the mongojs driver)?

How do I capture a MongoDB query as a string and display it in my Node JS page (using the mongojs driver)?

Problem

I would like to be able to Query my mongoDB and display this result on my web page made with Node...right now I am using the Mongojs Driver - I've found the driver very very good for putting data into the DB - the syntax is the same as the Mongo shell and I can put the code right in my Node app. This task...simply showing the results of the query on the webpage, or even on the console, has proven very difficult. Here are the relevant parts of my code and what I tried.

var databaseUrl = "test"; // "username:[email protected]/mydb"
var collections = ["graph1"]
var db = require("mongojs").connect(databaseUrl, collections);

console.log(db.graph1.find());

I have made a collection called graph1 and in the mongo prompt this yields results. Note...I do want to display it in HTML...but I spose if I can get it to print to console I can get it in my HTML.

It currently outputs this:

{_oncursor: { get: [Function], put: [Function] } } 

Some kind of prototype for what I actually want, which is this:

{ "x" : "0", "y" : "1343725568", "_id" : ObjectId("4fba6....") }
Problem courtesy of: PinkElephantsOnParade

Solution

Try this:

    db.graph1.find( {}, function(err, result ){ 
    if (err || !result ) console.log(" an error has occurred" );
    else {
    console.log(result);
    }
    });

The console log that you had there was printing the db.graph1.find() return value which is its Function prototype. It won't return anything useful because it's an asynchronous function. The only way to do useable things with the data it retrieves is to pass a callback in which will handle the data:

    db.graph1.find( { //what you want to search for here }, callback);

    function callback(result_from_mongo) {
    // do stuff here with result_from_mongo
    }
Solution courtesy of: Eoin Murray

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How do I capture a MongoDB query as a string and display it in my Node JS page (using the mongojs driver)?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×