Skip to content

Collection length does not match models length, when fetching and parsing data with duplicate ids #2976

Closed
@eschwartz

Description

Duplication Steps

  • Create a model, which parses it's id from an arbitrary response object attribute
  • Call fetch on a collection for the model
    • API returns multiple models with the same id
  • Call fetch a second time
    • API returns multiple models with the same id
  • Backbone throws error at 719:46 TypeError: Cannot read property 'cid' of undefined
set: function(models, options) {
      // ....

      // Remove nonexistent models if appropriate.
      if (remove) {
        for (i = 0, l = this.length; i < l; ++i) {
          if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
          // TypeError; this.models.length !== this.length
        }
        if (toRemove.length) this.remove(toRemove, options);
      }

      // ...
}

See Spec (failing) for mismatched collection length for a failing spec, duplicating this issue.

Expected Behavior

The root issue is clearly that the API is returning duplicate objects. However, I'm wondering if there might be a better way for Backbone to handle this situation, which would make the problem easier to trace.

What is the default behavior when adding a model to a collection with the same id as an existing model in the collection? I would expect an error to be thrown.

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions