Closed niallobrien closed 8 years ago
No it's not possible to add many-to-many relationship because the relations
module is still experimental. I will be working on it after releasing 1.0.0. It's in the RC state right now.
Is this available? I can' t seem to find documentation for it. Thanks
No it's still not available. Right now I'm focused on developing Astronomy 2.0 so it has to wait.
A many to many relationship can be easily solved with a combination of transient properties and a new "junction table" or in this case collection. I'll try to post some sample code.
Here's what I did in CoffeeScript @flean :D
Suppose Tags belong to many Products and Products belong to many Tags
@ProductsTags = new Mongo.Collection "products_tags"
@ProductTags = Astro.Class
relations:
tag_id:
type: "one"
class: "Tag"
local: "tag_id"
foreign: "_id"
product_id:
type: "one"
class: "Product"
local: "product_id"
foreign: "_id"
@Products = new Mongo.Collection "products"
@Product = Astro.Class
...
relations:
_tags:
type:"many"
class:"ProductsTags"
local:"_id"
foreign:"product_id"
methods:
tags: ->
@_tags().map (product_tags) ->
product_tags.tag()
@Tags = new Mongo.Collection "tags"
@Tag = Astro.Class
...
relations:
_products:
type:"many"
class:"ProductsTags"
local:"_id"
foreign:"tag_id"
methods:
products: ->
@_products().map (product_tags) ->
product_tags.product()
Note: This snippet isn't tested but it is a pretty close copy to what I have in one of my deployments.
Yes you can create separate collection for only storing ids of documents that are related. But there is also another way of doing many-to-many relation in MongoDB. You can store array of ids in both collections and you don't have to create new collection and that will be also possible in Astronomy 2.0 out of the box or at least that's the plant :)
That's great, I was thinking about doing that too but I wasn't sure how it would impact performance. Although, since you don't have an extra table when using arrays, I guess you remove a whole bunch of queries to the db so it should be considerably better right? I'm going to try that ^_^
@Lepozepo it's one of the possible solutions in MongoDB. Yes queries get much easier.
Just wondering if it's possible to do a many-to-many relationship? If so, can you provide an example please? Thanks.