zzarbi

Node.js/Mongo2

Feb 2nd, 2012
801
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var sys = require('sys'),
  2. http = require('http'),
  3. mongodb = require('mongodb');
  4.  
  5. var server = new mongodb.Server("127.0.0.1", 27017, {});
  6. var db = new mongodb.Db('mongo', server, {});
  7. var client  = null
  8.  
  9. db.open(function (error, clientParam) {
  10.     if (error) {
  11.         db.close();
  12.         throw error;
  13.     }
  14.     client = clientParam;
  15. });
  16.  
  17. http.createServer(function(req, res) {
  18.     var collection = new mongodb.Collection(client, 'basic');
  19.    
  20.     collection.find({'_id':String(Math.floor(Math.random()*100000))}, {}, function(err, cursor) {
  21.         if(err == null){
  22.          cursor.toArray(function(err, docs){
  23.              res.writeHead(200, {'Content-Type': 'text/html'});
  24.              res.write('Goood');
  25.              res.end();
  26.              //console.log(docs);
  27.          });
  28.         }else{
  29.             res.writeHead(200, {'Content-Type': 'text/html'});
  30.             res.write('Bad');
  31.             res.end();
  32.             throw err;
  33.         }
  34.     });
  35. }).listen(8080);
Advertisement
Add Comment
Please, Sign In to add comment