Advertisement
Guest User

Nodejs & MongoDB

a guest
Apr 2nd, 2012
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* GLOBALS
  2. ----------------------------------------------------------------------*/
  3. var rdata = [];
  4.  
  5. /* SERVER SETTINGS
  6. ----------------------------------------------------------------------*/
  7.  
  8. //load http module to ceate an http server.
  9. var http = require('http');
  10. var url  = require('url');
  11.  
  12. //configure to respond http server with message
  13. http.createServer(function (request, response) {
  14.    
  15.     //request name parameter
  16.     var url_parts = url.parse(request.url, true);
  17.     var query = url_parts.query;
  18.    
  19.     //do the mongo
  20.     var mongo = require('mongodb');
  21.     var db = new mongo.Db('nodedb', new mongo.Server('localhost', 27017, {}), {});
  22.  
  23.     db.open(function() {
  24.        
  25.         db.collection('Persons', function(err, collection) {
  26.        
  27.             var cursor = collection.find(query);
  28.            
  29.             cursor.each(function(err, doc) {
  30.                
  31.                 if(doc) {
  32.                
  33.                     rdata.push(doc);
  34.                    
  35.                 }
  36.                
  37.             });
  38.            
  39.         });
  40.            
  41.     });
  42.    
  43.     //write what type of response
  44.     response.writeHead(200, {'Content-Type': 'application/json;charset=utf-8'});
  45.    
  46.     //close response johan kvint :)
  47.     response.end(JSON.stringify(rdata));
  48.    
  49.     //clear rdata
  50.     rdata = [];
  51.    
  52. }).listen(process.env.PORT);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement