Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

backbone.js

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});
like image 820
Ananth Avatar asked Jan 10 '23 03:01

Ananth


1 Answers

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.

like image 143
mu is too short Avatar answered May 22 '23 10:05

mu is too short