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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.