The functions for connecting to and querying a mongodb database (I'm assuming most types of databases, by the nature of node) are non-blocking. How do I write a function to get the results of a query in, say, a JSON object? the function should manage the querying and block until the query is returned.
Basically I want to be able to do something like this:
http.createServer(function(request,response){
var searchQuery = parseQueryFromUrl(request.url);
var searchResults=queryDatabase(searchQuery);
var document = renderFile(fileTemplate,searchResults);
response.writeHead(200);
response.write(document);
response.end();
});
Is this possible?
writing from the phone, here quick answer, will edit when I get home later:
router.get('/search/*', function(req, res, term){
res.writeHead(200, {'Content Type:':'text/plain'});
var db = new mongo.Db('dbname', server);
db.open(function(err, db){
db.createCollection("collection_name", function(err, collection){
db.collection('foo').find({'a':term}).toArray(function(err, items){
console.log(items);
});
});
});
});
here more about queries: http://mongodb.github.io/node-mongodb-native/markdown-docs/queries.html