Reputation: 1
I'm trying to query a MongoDB database in Node and display output based on the result. I can check the database and pull the record just fine, and I can work with the record, compare it to other variables, etc., but when I try to send a response, it doesn't display anything. Some sample code below:
request.addListener('data',function(chunk){
post+=chunk;
}).addListener('end',function(){
var forminfo = querystring.parse(post);
db.collection('users',function(err,collection){
collection.findOne({'field1':forminfo.val1,'field2':forminfo.val2},function(err, document){
//responses go bad here
if(document){
console.log("Ok");
response.writeHead(200);
response.write("Ok");
response.end();
}
else{
console.log("Bad");
response.writeHead(200);
response.write("Bad");
response.end();
}
});
});
});
When I try my code like this, it's like the server response calls are never made. I've tried adding callback functions, to no avail. Trying to return a boolean so I can write output results in the output being sent before the database is successfully queried. The POST data is making it through fine, and the record search returns the expected values.
Upvotes: 0
Views: 595
Reputation: 614
I m also trying to query MongoDB in node.js (node.js 0.43 / MongoDB 1.8 / node-mongodb-native 0.9.1). The below code can return query result and write to response. See if it helps.
var http = require('http'),
qs = require('querystring');
Db = require('mongodb').Db,
Connection = require('mongodb').Connection,
Server = require('mongodb').Server,
host = 'localhost',
port = Connection.DEFAULT_PORT;
var db = new Db('test', new Server(host, port, {}), {});
db.open(function(err, db) {
var server = http.createServer(function (request, response) {
var data = '';
if (request.method === "POST") {
request.addListener('data', function (chunk) {
data += chunk;
});
request.addListener('end', function() {
response.writeHeader(200, {'Content-Type': 'text/html'});
var post = qs.parse(data);
db.collection('user', function(err, collection) {
collection.findOne({'name': post.name}, {}, function(err, user) {
if (user != null) {
response.write(user.name);
console.log(user);
} else {
response.write('user not found');
console.log('user not found');
}
response.end('<form method="POST" action="">' +
'<input type="text" name="name" value="' + post.name + '"/>' +
'<input type="submit" value="submit" />' +
'</form>');
});
});
});
} else {
response.writeHeader(200, {'Content-Type': 'text/html'});
response.end('<form method="POST" action="">' +
'<input type="text" name="name" />' +
'<input type="submit" value="submit" />' +
'</form>');
}
});
server.listen(8000);
});
Upvotes: 1