Search code examples
model-view-controllersails.jssails-mongo

How to do query with dynamic numbers of condition with SailsJS and MongoDB


I'm using SailsJS with MongoDB. For the Model "accounts" I'm using below code:

attributes: {   
    campaignID : { type: 'string' },
    cell : { type: 'string' },
    firstname : { type: 'string' },
    lastname : { type: 'string' },
    ssn : { type: 'integer' }
  }

And the problem is I don't how to write code to query the model in a way I can put any number of condition for the attributes in the model. For example one query could be query all that with cell="5" And ssn="123456789" Another query can be query all that with lastname="Borune". Current I implemented below code in the controller:

list: function(req,res) {
        Accounts.find().where({
            campaignID' : {
                contains : req.param('campaignID')
            },
            cell:{
                contains : req.param('cell')
            }
        }).exec(function(err,data){
            if (err) res.json({error:'true'});
            res.json(data);
        });     
    }

But the problem is when I only want to use one attribute for the condition such as below address, no document will be returned since cell is not defined in the parameter.

http://localhost:1337/search?campaignID=testID2

How do I write the condition code so that I can specify any number of the condition as above and get the document that matches all the conditions.


Solution

  • Just form your search criteria before you actually try to find anything. In case you're using query string to pass parameters (i.e. /search?campaignID=foo&cell=42) this should be something like:

    list: function(req,res) {
      // req.query is {campaignID: 'foo', cell: '42'}
      var criteria = _.mapValues(req.query, function(val) {
        return {contains: val};
      })
      // criteria is {campaignID: {contains:'foo'}, cell: {contains: '42'}}
      Accounts.find(criteria).exec(function(err,data){
        if (err)  {
          return res.json({error:'true'});
        }
        res.json(data);
      });     
    }
    

    If you want to use request payload instead of query string you should change req.query to req.body.

    Don't forget var _ = require('lodash') on the top of controller file if you don't add it to sails autoload via config.