How to take a MongoDB request as a string and display it on my Node JS page (using the mongojs driver)?

I would like to be able to query my mongoDB and display this result on my web page made using Node ... right now I am using the mongojs driver - I found that the driver is very good for placing data in the database - the syntax is the same as Mongo shell and I can put the code in my Node application. This task ... just showing the results of a query on a web page or even on the console turned out to be very difficult. Here are the relevant parts of my code and what I tried.

var databaseUrl = "test"; // "username:password@example.com/mydb"
var collections = ["graph1"]
var db = require("mongojs").connect(databaseUrl, collections);

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

I created a collection called graph1 and in the mongo tooltip this gives the results. Note ... I want to display it in HTML ... but I spose, if I can get it to print to the console, I can get it in my HTML.

He is currently outputting this:

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

Some kind of prototype of what I really want is this:

{ "x" : "0", "y" : "1343725568", "_id" : ObjectId("4fba6....") }
+5
source share
2 answers

Try the following:

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

In the console log you were in, the return value db.graph1.find () was printed, which is its function prototype. It will not return anything useful, because it is an asynchronous function. The only way to do useful things with the data it retrieves is to go through a callback in which the data will be processed:

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

    function callback(result_from_mongo) {
    // do stuff here with result_from_mongo
    }
+2
source

For security reasons, everyone should know that the only time you can manipulate the results of your query is DEPENDENCE ... therefore you should not bind it to var in order to cheat later, only in the callback) - =.

, . .:

  var results_not_ugly_or_messed_up = (JSON.stringify(result));

, perl/python/sh/bat/whatever script "" ( , results_not_ugly_or_messed_up) , .., , , .

:

db.newguestbook.find({"Name" : /[Aa]/ },[],function(err,p) //newguestbook is a collection I have    
//you will need to change that unless you make a collection called newguestbook
{
    cursor = p;
    console.log(cursor);
    console.log(JSON.stringify(cursor))); //We have a nice string, see?
    var exec = require('child_process').exec;
    exec("perl writetofile.pl " + JSON.stringify(cursor) , function(err, 
    stdout, stderr)
    {
        console.log("Perl run to store this result in a file");
    });

});
}
+1

All Articles