Foreign keys in mongo?

Viewed 157436

enter image description here

How do I design a scheme such this in MongoDB? I think there are no foreign keys!

7 Answers

Short answer: You should to use "weak references" between collections, using ObjectId properties:

References store the relationships between data by including links or references from one document to another. Applications can resolve these references to access the related data. Broadly, these are normalized data models.

https://docs.mongodb.com/manual/core/data-modeling-introduction/#references

This will of course not check any referential integrity. You need to handle "dead links" on your side (application level).

The purpose of ForeignKey is to prevent the creation of data if the field value does not match its ForeignKey. To accomplish this in MongoDB, we use Schema middlewares that ensure the data consistency.

Please have a look at the documentation. https://mongoosejs.com/docs/middleware.html#pre

I see no reason why you cannot use a NOSQL db as a relational DB since you have aggregate pipelines which you can use to create views like SQL inner joins.

Each collection should contain one type e.g. order and order-details is a 1:M relation.

ORDER COLLECTION
id (PK) Type: GUID
OrderNo (candidate or alternate PK)
OrderDate
Customerid (FK)
...more order fields

ORDER-DETAILS COLLECTION
id (PK)
Orderid (FK)
Productid (FK)
Qty
...more fields

PRODUCT
id (PK)
Supplierid (FK)
Name
Cost

And so on.

The reason why you would not simply use a relational database is because a NOSQL database has other features you could use in tandem with relationally designed data collections.

The way you implement the relations is the same as in relational databases. You have to add the foreign keys yourself (primary keys are added automatically for each document object) and create the normalized join collections. A database will not normalize itself usually.

The only caveat is that you have to code referential integrity yourself as NOSQL does not do that (yet). So in your admin UI if a user tries to delete a parent that has children you throw a friendly error saying they have to delete the children first. It is not hard but you still need to be careful when using DB utilities not to delete a parent that has children because the DB will let you.

Always use the naming conventions for foreign keys id. For example:

ORDER-DETAIL COLLECTION
id (PK)
Orderid (FK) .... you an easily deduce that this foreign key is the primary key in the Order collection by sticking to this naming convention.

Related