Search code examples
backbone.jscollectionsmodels

Merge local Backbone collection with server


I have a local Backbone collection:

var collection = new Backbone.Collection([ { greeting: "hi" }, { greeting: "bye" } ]);

I understand that when I run collection.fetch, Backbone will run collection.set on the results. I need to merge in the response from the server, however. Say the response is:

[ { id: "2", greeting: "hi", name: "Bob" } ]

I would like the resulting collection, after the merge, to be:

[ { id: "2", greeting: "hi", name: "Bob" }, { greeting: "bye" } ]

I understand Backbone already attempts to do some merging here, but if I set the example response above, no merge happens and a new model gets added instead. I assume this is because it merges by id, and here we do not have any ids (in the local collection). In this case, greeting is my unique identifier / key.

The reason I am trying to do this is because I have a local collection and I simply want to see what already exists from that collection (using the key greeting) and merge any findings in.


Solution

  • My solution:

    feeds.fetch({
      add: false,
      remove: false,
      merge: false,
      data: params,
      success: function (feeds, response) {
        // Merge any matches
        _.each(response.results, function (result) {
          _.each(feeds.models, function (feed) {
            // We have to `parse` the result before setting it, as Model#set does
            // not automatically run `parse` (Collection#set does).
            result = feed.parse(result)
            if (feed.get('rssUrl') === result.rssUrl) feed.set(result)
          })
        })
        cb(feeds)
      }
    })