0

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?

1
  • 1
    This has been asked/answered many times before. What didn't make sense? Node is async, so you'll need to use callbacks, or an object layer like Mongoose which can also expose Promises. Commented Apr 27, 2014 at 20:46

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! But I'm trying to put the whole db.open(...) function in another function to add some abstraction, to keep the code cleaner. Is that possible?
can you edit your question and show what you have so far? and yes it is possible

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.