I'm having a heckuva time understanding the documentation for Backbone-Relational; it's not 100% clear on which relation to add things like includeInJSON
. Probably best to describe my confusion by illustrating the structure I'm trying to create. I have a Venue
model that has zero or more nested Address
models (1:n relationship). The backend store is MongoDB, which can have embedded objects. I'd like to store it in this format:
{
id: 12345,
label: 'OPUS Cafe Bistro',
addresses: [
{
type: 'mailing',
address1: '#52 - 650 Duncan Ave',
city: 'Penticton, BC'
},
{
type: 'main',
address1: '#106 - 1475 Fairview Rd',
city: 'Penticton, BC'
}
]
}
(Please ignore the ugly data structures; I've adjusted it for brevity.) Now I believe I set up the relationship between Venue
and Address
thusly:
var Venue = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone.HasMany,
key: 'addresses',
relatedModel: 'Address',
includeInJSON: false,
collectionType: 'Addresses',
reverseRelation: {
key: 'venue'
}
}
});
If I understand correctly, I set includeInJSON
to false in order to prevent the Venue
from being serialised into the venue
key in Address
, but under reverseRelation I leave includeInJSON
blank in order to have the full Address
(without a venue property) serialised as an array in the addresses
property of the Venue
– as per my hoped-for example. Correct?
By the same token, I'm trying to understand the same concept in relation to a join-style relationship. Consider that Venue
now has an organisationID
field:
/* venue in JSON format */
{
id: 12345,
organisationID: 336,
label: 'OPUS Cafe Bistro',
addresses: []
}
/* and now for the organisation */
{
id: 336,
label: 'OPUS Entertainment Group'
}
Using the examples in the documentation, which seem to prefer the Backbone.HasMany
relationship, I think that I'd have to set up Organisation
thus:
var Organisation = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone:HasMany,
key: 'venues',
relatedModel: 'Venue',
includeInJSON: Backbone.Model.prototype.idAttribute,
collectionType: 'Venues',
reverseRelation: {
key: 'organisationID',
includeInJSON: false
}
}
]
});
... which should serialise into the above example, right? (I.e., Venue
grabs Organisation
's id
and inserts it into organisationID
, and Organisation
doesn't serialise any list of Venues
)
Thanks in advance for any help – looking forward to using this handy library, after clawing my eyeballs out trying to write my own relational glue for Backbone.js :-)