如何从函数中查询node.js中的mongoDB?

时间:2023-01-22 16:09:36

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.

连接和查询mongodb数据库的功能(我假设大多数类型的数据库,根据节点的性质)是非阻塞的。如何编写一个函数来获取查询结果,比如JSON对象?该函数应该管理查询和阻塞,直到返回查询。

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


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

这里有关于查询的更多信息:http://mongodb.github.io/node-mongodb-native/markdown-docs/queries.html

#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

这里有关于查询的更多信息:http://mongodb.github.io/node-mongodb-native/markdown-docs/queries.html