user2038580 user2038580 - 7 months ago 16
Javascript Question

Not able to pass parameter to mongo find collection

Req.params gets value after db.collection.find executes. Can Some one tell me what I am doing wrong with this code?

exports.findAll = function(req, res) {
var postal = parseInt(req.params.postal);
db.collection('ifscdata', function(err, collection) {
collection.find({'ADDRESS':/postal/}).toArray(function(err, items) {
res.send(items);
});
});


Am supposed to do a partial search on address based on postal. But am not able to pass the value to postal because its getting the value only afterwards.

Function route is this

app.get('/ifsc/:postal', ifsc.findAll);


Sample URL :


http://localhost:3000/ifsc/691009

Answer

Looks like you need to use regex within your query, consider wrapping the variable with the RegExp object as follows:

exports.findAll = function(req, res) {
    var postal = req.params.postal, 
        regex = new RegExp(postal);

    db.collection('ifscdata', function(err, collection) {
        collection.find({'ADDRESS': regex}).toArray(function(err, items) {
            res.send(items);
        });
    });