Mongo Relationships
We usually have a lot of data and they are interconnected to each other.
SQL Relationships Overview
- Have independent tables and they reference each other to have relationships.
- To keep up with Many to Many relationships, it is common to create another table that only references other tables.
One to Few
- Embed the data directly in the document
- Example
{
name : 'Tommy Cash',
savedAddresses: [
{ Tallinn, Estonia },
{ NY, USA }
]
}
One to Many
- One option is to store your data separately, but then store references to document IDs somewhere inside the parent.
- Example
{
farmName : 'Full Belly Farms',
location : 'Guinda, CA',
produce : [
ObjectId('2346744'),
ObjectId('9467566'),
ObjectId('4367636')
]
}
//When making the Schema, use this:
//produce: [{type: mongoose.Schema.Types.ObjectId, ref: 'Produce'}]
//ObjectId is a Mongoose object. When type is set to ObjectId,
//it just adds ObjectId, not the whole object.
//ref tells mongoose which model we're going to populate it with.
//In this case, it's 'Produce', which is a name of customized mongoose class.
Mongoose Populate
- Populated paths are no longer set to their original _id, their value is replaced with the mongoose document returned from the database by performing a separate query before returning the results.
- Example
Story.
findOne({title: 'Casino Royale'}).
populate('author').
exec(function (err, story) {
if(err) return handleError(err);
console.log('The author is %s', story.author.name);
//prints "The author is Ian Fleming"
})
One to "Bajillions'
- With thousands or more documents, it's more efficient to store a reference to the parent on the child document.
- Example
{
tweetText: 'lol I just crashed my car',
tags : ['car', 'accident'],
user: ObjectId('2045835')
}
* This post is a summary of Udemy Course "The Web Developer Bootcamp" by Colt Steele.
'TIL: Today I Learned' 카테고리의 다른 글
[TIL] 20201226 Express Session & Flash (0) | 2020.12.26 |
---|---|
[TIL] 20201222 Express Router & Cookies (0) | 2020.12.22 |
[TIL] 20201219 Handling Errors in Express Apps (0) | 2020.12.19 |
[TIL] 20201218 Middleware: The Key To Express (0) | 2020.12.19 |
[TIL] 20201217 MongoDB / Mongoose (0) | 2020.12.17 |