4

I want to make an HTML form to query MongoDB. How can I write the logic to ignore blank fields? For example, I have two search parameters. If the lastname field is blank, how would I write the query to ignore that field?

router.post('/auth/search', auth, function(req,res){
    var db = req.db;
    console.log(req.body);
    db.users.find({ 'firstname': req.body.firstname,
                    'lastname' :req.body.lastname  // if this field is blank in the form how can I ignore it?

    }, function(err, docs){
        if (err) return err;
        console.log(docs);
        res.send(docs);
    });
});

Appreciate any help. Thanks!

Stennie
  • 63,885
  • 14
  • 149
  • 175

2 Answers2

6

You can add properties to your query only if they’re truthy:

var query = {};

if (req.body.firstname) {
    query.firstname = req.body.firstname;
}

if (req.body.lastname) {
    query.lastname = req.body.lastname;
}

db.users.find(query, function (err, docs) {
    // …
});
Ry-
  • 218,210
  • 55
  • 464
  • 476
-2

By making search object dynamically.

router.post('/auth/search', auth, function(req,res){
    var db = req.db;
    console.log(req.body);
    var obj = {}
    if(req.body.firstname) {
        obj['firstname'] = req.body.firstname;
    }
    if(req.body.lastname) {
        obj['lastname'] = req.body.lastname;
    }

    db.users.find(obj, function(err, docs){
        if (err) return err;
        console.log(docs);
        res.send(docs);
    });
});
Harpreet Singh
  • 2,651
  • 21
  • 31
  • 3
    `curl -d '$where=function () { while (true); }'` says “don’t do that”. – Ry- Jul 06 '14 at 17:30
  • 2
    @HarpreetSingh, it's a matter of whitelisting/sanitizing your inputs. You don't want to openly trust any parameter that's being sent from the end user. – maček Jul 06 '14 at 17:49
  • Oh yes, sure it would be a big mistake. Though I know that but slipped from mind this time. Now it will be remembered forever. Thanks :) – Harpreet Singh Jul 06 '14 at 17:58