简体   繁体   中英

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.

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM