I am trying to filter a backbone collection to return only models that match a couple of attributes, I am wanting to return only models that have an owner_id that is null, and a user_id that is equal to "1". Here is my code,
myFilter: function( owner_id, user_id) {
console.log(owner_id, user_id);
var filtered = this.filter(function(user) {
return user.get("owner_id") === owner_id && user.get("user_id") === user_id});
return new App.Collections.MyClients(filtered);
}
I know there are 2 matching records in my collection, but I only ever get the first returned, why is this?
The collection data looks like this,
id name information type user_id owner_id
18 Client 1 client 1 NULL
19 Client 2 client 1 32
20 Client 3 client 1 NULL
The user_id gets return as a string
From looking at the collection data you posted the most obvious answer seems to be that your
MyClientmodel has anidAttributeofuser_id.A Backbone Collection cannot contain duplicated models, duplicated in this case meaning models with the same
idAttribute.Assuming an
idAttributeofuser_id, when you call:return new App.Collections.MyClients(filtered);your
MyClientscollection will only contain the first model with auser_idof 1, despite yourfilteredobject containing multiple models with auser_idof 1.From the
setmethod in the backbone annotated source code: