Search code examples
javascriptbackbone.jsmodel

Backbone JS - Model returns two results instead of one


I've been fiddling around with backbone and im trying to retrieve a single result by fetching with a certain ID.

Model:

var Recipe = Backbone.Model.extend({
    urlRoot: 'recipes',
  initialize: function() {
    this.fetch();
    console.log("A new recipe has been loaded.");
  },
});

var recipe = new Recipe({id: id});

recipe.toJSON() // Returns:

Returns:

Object {0: Object, id: "1"}

This returns the object containing all my data and a id field containing the id that im setting in new Recipe({id: id}).

Why is it doing that? I thought a model that was fetching with a specific ID was going to retrieve a single result. Or am I doing it wrong?

Best regards, Jake


Solution

  • parse the data before assigning to model

    var Recipe = Backbone.Model.extend({
        urlRoot: 'recipes',
    
       parse : function(response){
       return response[0];
       },
      initialize: function() {
        this.fetch();
        console.log("A new recipe has been loaded.");
      },
    });