filtering backbone collection on return 1 results

60 Views Asked by At

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

1

There are 1 best solutions below

0
On

From looking at the collection data you posted the most obvious answer seems to be that your MyClient model has an idAttribute of user_id.

A Backbone Collection cannot contain duplicated models, duplicated in this case meaning models with the same idAttribute.

Assuming an idAttribute of user_id, when you call:

return new App.Collections.MyClients(filtered);

your MyClients collection will only contain the first model with a user_id of 1, despite your filtered object containing multiple models with a user_id of 1.

From the set method in the backbone annotated source code:

// If a duplicate is found, prevent it from being added and optionally merge it into the existing model.
if (existing = this.get(id)) {
  if (remove) modelMap[existing.cid] = true;
    if (merge) {
      attrs = attrs === model ? model.attributes : attrs;
      if (options.parse) attrs = existing.parse(attrs, options);
      existing.set(attrs, options);
      if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
    }
    models[i] = existing;
  }
}