javascriptbackbone.jsbackbone-relational

How to not remove duplicates in collection in backbone


I create backbone collection from server JSON. Data is from mongo so each item has same objects and backbone remove this duplicates. It's unwanted behavior for me so, I can't find solution to keep this instances. After fetch my items has only 'section1' in secound object (id:2). I need the same section also in first object. For example my server response is:

items:  [{
  id:1,
  sections: [{
    id: 1.//this object is removed
    name: 'section1'
   }] 
}, {
  id: 2,
  sections: [{
    id:1.
     name: 'section1'
  }]
}]

My section model is just:

Section = Backbone.RelationalModel.extend({
});

and Item model:

Item = Backbone.RelationalModel.extend({
            relations: [
                {
                    'type': 'HasMany',
                    'key': 'sections',
                    'relatedModel': 'Section',
                    'includeInJSON': 'id',
                    'reverseRelation': {
                        'key': 'item',
                        'includeInJSON': 'id'
                    }
                }
            ]
});

Solution

  • If I recall correctly, this plugin doesn't support many-to-many. So, what's happening is that it is attaching Section 1 to the first Item, then attaching it to the second and removing it from the first.

    In fact, from the docs:

    Backbone.HasMany

    Defines a HasMany relation. When defining a reverseRelation, the type will be HasOne.

    Your options:

    1. Create a SectionItem model that HasOne Section and HasOne Item. Someone posted a fiddle with this sort of setup http://jsfiddle.net/mmacaula/XaESG/2/
    2. Use another library - or an extension of the one you use, like https://github.com/jj-studio/Backbone-JJRelational
    3. Add a property to the Section model key that would make each one unique. This is not a good way to achieve what you are trying to do, though.

    Here is a pretty good reference answer: Implementing a Many-to-Many relationship with Backbone-Relational