Hello all :) My problem is that is not working response.vrite () Why ? And another question. Will be called db.open each boot / upgrade page?
var http = require("http");
var Db = require ("mongodb").Db;
var Server = require("mongodb").Server;
function start () {
'use strict';
function onRequest (request, response) {
'use strict';
var db = new Db ("TestApp", new Server ("127.0.0.1", 27017, {}));
response.writeHead(200, {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"});
db.open (function (err, db, response) {
db.collection ('ObjectCollection', function (err, collection) {
collection.find().toArray (function (err, docs) {
console.log (docs);
response.write(JSON.stringify(docs));
});
});
});
response.end();
}
http.createServer(onRequest).listen(8080);
console.log ('Server has started...')
}exports.start = start;
You're calling response.end
before your response.write
. Move the response.end
call inside the callbacks like this:
var http = require("http");
var Db = require ("mongodb").Db;
var Server = require("mongodb").Server;
function start () {
'use strict';
function onRequest (request, response) {
'use strict';
var db = new Db ("TestApp", new Server ("127.0.0.1", 27017, {}));
response.writeHead(200, {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"});
db.open (function (err, db, response) {
db.collection ('ObjectCollection', function (err, collection) {
collection.find().toArray (function (err, docs) {
console.log (docs);
response.write(JSON.stringify(docs));
response.end();
});
});
});
}
http.createServer(onRequest).listen(8080);
console.log ('Server has started...')
}
exports.start = start;
And yes, a new Db
object will be opened on each request so it would be better to open that once during startup.
Like Johnny said, your calling response.end() outside of your asynchronous functionality. As a rule, you should never count on callbacks actually executing in a blocking manner unless you KNOW how their parent function works under the hood. DB.open likely runs that callback upon connection completion, and we don't know how long that will take. Since DB.Open is non-blocking, node then executes the response.end before DB.open's asynchronous call to the database likely even completes. You may want to read up a bit on asynchronous javascript