Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Node.js parameter into mongodb request

I'm working on a simple web service in node.js. I'm using choreographer to route the http calls. This code works fine:

router.get('/search/*', function(req, res, term){
  res.writeHead(200, {'Content Type:':'text/plain'});
  db.collection('foo').find({'a':1}).toArray(function(err, items){
  console.log(items);
    res.write(JSON.stringify(items));
    res.end();
   });
  });

As you can see, the find method looks for {'a':1}, this works fine, a record is returned. But when I want to pass the search term from the router to the query I get a null response:

router.get('/search/*', function(req, res, term){
  res.writeHead(200, {'Content Type:':'text/plain'});
  db.collection('foo').find({'a':term}).toArray(function(err, items){
  console.log(items);
    res.write(JSON.stringify(items));
    res.end();
   });
  });

Any ideas anyone??

Edit: I have checked the value of term, as suggested below in the comments, it is 1, which is what I expected it to be.

like image 616
2bard Avatar asked Mar 19 '26 00:03

2bard


2 Answers

Could it be that the db-connection takes longer than the actually routing?

If you define "term" and get a reponse it is most likley the term is not found in db or the db-connection fails in some way.

A way could be to init and call db from a callback function.

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);
      });
    });
  });
});

If it work you may want to throw in a db.close();

Reservation for bad syntax.

like image 102
Rickard Zachrisson Avatar answered Mar 20 '26 12:03

Rickard Zachrisson


I found a workaround was to build up a new json object then set the 'a' parameter to term afterwards e.g.

var searchterm = {'a':2};
searchterm.a = term;

I suspect there is something about creating JSON objects i'm not fully understanding here.

like image 33
2bard Avatar answered Mar 20 '26 14:03

2bard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!