Search code examples
backbone.js

Backbone - findWhere : How to find a model by querying for a nested object


Here's my collection's sample set:

{
    "name": "Bob",
    "class": "3",
    "marks": {
        "maths": 70,
        "science": 85
    }
},
{
    "name": "Ron",
    "class": "3",
    "marks": {
        "maths": 80,
        "science": 90
    }
}

With Backbone's findWhere, I'm able to get the model given the query like this:

Coln.findWhere({"name": "Ron"});

But how do I query the model based on maths mark? The below code doesn't seem to work:

Coln.findWhere({"marks.maths": 80});

Solution

  • Collections have various Underscore methods mixed into them. In particular, there is find which lets you specify a predicate function so you could do something like this:

    Coln.find(function(m) { return m.get('marks').maths === 80 })
    

    If you wanted to find all the models that matched, use filter.