Collections
OneToMany
and ManyToMany
collections are stored in a Collection
wrapper. It implements
iterator so you can use for of
loop to iterate through it.
Another way to access collection items is to use bracket syntax like when you access array items.
Keep in mind that this approach will not check if the collection is initialed, while using get
method will throw error in this case.
Note that array access in
Collection
is available only for reading already loaded items, you cannot add new items toCollection
this way.
#
OneToMany CollectionsOneToMany
collections are inverse side of ManyToOne
references, to which they need to point via fk
attribute:
#
ManyToMany CollectionsFor ManyToMany, SQL drivers use pivot table that holds reference to both entities.
As opposed to them, with MongoDB we do not need to have join tables for ManyToMany
relations. All references are stored as an array of ObjectId
s on owning entity.
#
UnidirectionalUnidirectional ManyToMany
relations are defined only on one side, if you define only entity
attribute, then it will be considered the owning side:
#
BidirectionalBidirectional ManyToMany
relations are defined on both sides, while one is owning side (where references are store),
marked by inversedBy
attribute pointing to the inverse side:
And on the inversed side we define it with mappedBy
attribute pointing back to the owner:
#
Forcing fixed order of collection itemsSince v3 many to many collections does not require having auto increment primary key, that was used to ensure fixed order of collection items.
To preserve fixed order of collections, you can use fixedOrder: true
attribute, which will
start ordering by id
column. Schema generator will convert the pivot table to have auto increment
primary key id
. You can also change the order column name via fixedOrderColumn: 'order'
.
You can also specify default ordering via orderBy: { ... }
attribute. This will be used when
you fully populate the collection including its items, as it orders by the referenced entity
properties instead of pivot table columns (which fixedOrderColumn
is). On the other hand,
fixedOrder
is used to maintain the insert order of items instead of ordering by some property.
#
Propagation of Collection's add() and remove() operationsWhen you use one of Collection.add()
method, the item is added to given collection,
and this action is also propagated to its counterpart.
For M:N this works in both ways, either from owning side, or from inverse side.
Collections on both sides have to be initialized, otherwise propagation won't work.
Although this propagation works also for M:N inverse side, you should always use owning side to manipulate the collection.
Same applies for Collection.remove()
.
#
Filtering and ordering of collection itemsWhen initializing collection items via collection.init()
, you can filter the collection
as well as order its items:
You should never modify partially loaded collection.