Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce foreign keys in NoSql databases (MongoDB)?

Tags:

Let's say I have a collection of documents such as:

{ "_id" : 0 , "owner":0 "name":"Doc1"},{ "_id" : 1 , "owner":1, "name":"Doc1"}, etc

And, on the other hand the owners are represented as a separate collection:

{ "_id" : 0 , "username":"John"}, { "_id" : 1 , "username":"Sam"}

How can I make sure that, when I insert a document it references the user in a correct way. In old-school RDBMS this could easily be done using a Foreign Key.

I know that I can check the correctness of insertion from my business code, BUT what if an attacker tampers with my request to the server and puts "owner" : 100, and Mongo doesn't throw any exception back.

I would like to know how this situation should be handled in a real-word application.

Thank you in advance!

like image 928
Ariel Chelsău Avatar asked Nov 19 '11 15:11

Ariel Chelsău


People also ask

How do I add a foreign key in NoSQL?

NoSQL databases are much more flexible in format, structure, and schema. NoSQL does not imply that no SQL is used—in fact, most support a SQL-like query language—but that the database is non-relational. NoSQL databases do not support foreign keys or joins and do not have the concept of referential integrity.

How does foreign key work in MongoDB?

The foreign keys can be used in the Relational Databases for visualizing data from multiple collections simultaneously. The way MongoDB stores data is also different. Instead of using tables, columns, and rows, MongoDB uses collections, objects, and fields.

Does NoSQL have primary key and foreign key?

The non-relational database, or NoSQL database, stores data. However, unlike the relational database, there are no tables, rows, primary keys or foreign keys. Instead, the non-relational database uses a storage model optimized for specific requirements of the type of data being stored.

Do NoSQL databases have keys?

Unlike relational databases, NoSQL databases are based on key-value pairs. Some store types of NoSQL databases include column store, document store, key value store, graph store, object store, XML store, and other data store modes. Usually, each value in the database has a key.


1 Answers

MongoDB doesn't have foreign keys (as you have presumably noticed). Fundamentally the answer is therefore, "Don't let users tamper with the requests. Only let the application insert data that follows your referential integrity rules."

MongoDB is great in lots of ways... but if you find that you need foreign keys, then it's probably not the correct solution to your problem.

like image 78
mdahlman Avatar answered Sep 24 '22 02:09

mdahlman