Search code examples
javascriptbackbone.jsfirebasebackfire

Performing a fetch on a model using the Backfire bindings does not retrieve any data


Using the officially supported backbone.js bindings for Firebase I cannot seem to retrieve any data from a model in my Firebase.

For example, I want to fetch all of the information for user #2 stored under the Firebase reference:

https://app.firebaseio.com/users/2

To do this I would create a new user model with the ID specific to my user and call fetch on that model:

var ProfileModel = Backbone.Model.extend( {

    initialize: function () {
        console.log('Profie Model');
    },

    firebase: new Backbone.Firebase("https://app.firebaseio.com/users"),

});

var userProfile = new ProfileModel({id: "2"});
userProfile.fetch({
  success: function (model, response, options) {
    console.log(model);
    console.log(response);
    console.log(options);
    userProfile.set({test: "test value"});
    userProfile.save();
  },
  error: function () {
    alert('Something went wrong!');
  }
});

In this snippet the success callback is fired but no data is added to the model from Firebase and the response is returned as undefined. However, when the test value is set on the model and then save() is called the data is saved correctly into Firebase.

I am assuming urlRoot does not need to be set on the model as the bindings use the id property to create the path to user #2.

As stated in the readme, when the firebase object is added to a model or collection it overrides backbone sync to use Firebase instead. Any suggestions would be greatly appreciated before I start digging into the bindings themselves.


Solution

  • If the data you are trying to retrieve hasn't been written by Backfire, then the data will not be read correctly. If you are trying to read existing data, make sure it is of the form:

    /users
      /2
        /id: 2
        /attribute1: "foo"
        /attribute2: "bar"
    

    Most likely, https://app.firebaseio.com/users/2/id is not defined in your Firebase, and Backfire doesn't recognize it has a valid model.

    This is also why the second time you save data, the callback gets the correct data - if you look at the data in forge, you'll see:

    /users/2
      /id: 2
      /test: "test value"
    

    Hope this helps!