1

I am fairly new to javascript, and I want to use node.js to query a mongodb database in order to pass it to an http server.

So far, I have successfully set up a "Hello, world!" http server using this script:

var http = require('http');

http.createServer(function (req, res) {
       res.write('Hello World!');
       res.end();
}).listen(8080);

I've also been able to query my mongodb database and print the results to the console:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/MYDB";

MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        db.collection("collection").find({}).toArray(function(err, result) {
                if (err) throw err;
                console.log(result);
                db.close();
        })
});

However, I am unable to pass the results of my query to the res object of the http server. I would like to do something like this:

var http = require('http');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/MYDB";

http.createServer(function (req, res) {
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        db.collection("collection").find({}).toArray(function(err, result) {
            if (err) throw err;
            var query = result;
            db.close();
        })
    });

    res.write(query);
    res.end();

}).listen(8080);

When I try to create the query variable inside of the the MongoClient connection and use it later, I get an error that query is not defined. I can't find any examples of MongoClient.connect that don't simply print the result to the console, so I'm stuck.

Thanks for the help.

1 Answer 1

5

db.collection("collection").find({}) is async function, you should send the result to the client inside of the callback:

http.createServer(function (req, res) {
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        db.collection("collection").find({}).toArray(function(err, result) {
            if (err) throw err;
            var query = result;
            db.close();
            res.write(query);
            res.end();
        });
    });
}).listen(8080);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.