Reputation: 2583
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.
Upvotes: 3
Views: 2920
Reputation: 2583
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.
Upvotes: 1
Reputation: 985
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.
Upvotes: 1