3

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.

3
  • Did you check the value of term ?? console.log(term) Commented Dec 5, 2011 at 18:35
  • simplyharsh, yes I have, it is as expected Commented Dec 5, 2011 at 18:41
  • Have you checked the value of err? If there are any problems executing the query, err will be non-null and items will be null. It's good to always check. Commented Dec 5, 2011 at 20:53

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

'term' (1) is definitely in the database, the variable 'term' has been initialized correctly when the database is queried
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.