Data Associations
- will allow us to have multiple pieces of data, multiple collections in our database that are
related to one another --- important to making more complicated apps
- example: with a site like Facebook there are models for User, Post, Photos, Albums
, Comments, Tags, Likes, etc.
- all these are interconnected
Types of Associations
- one:one relationships
- simplest
- have one of an entity that is related to one of another entity
- examples:
- one book has one publisher
- one employee has one title
- one:many relationships
- one entity is related to many of another entity
- example:
- Facebook --- one user can have multiple photos, but the photos only belong to one user
- many:many relationships
- examples:
- school --- each student has multiple courses, but each course also has multiple students
- an author can have many books, but books can also have multiple authors
Embedding Data
- note: examples use Mongoose --- they will use User and Posts to model a one:many relationship
- examples located in 'the-web-developer-bootcamp/15_data_associations/embed.js'
- this gives us users that look like this:
{
email:'asdas',
name: 'asdas',
posts: [
{title: 'asdas', content: 'asdas'},
{title: 'asdas', content: 'asdas'},
{title: 'asdas', content: 'asdas'}
]
}
Referencing Data
- note: examples use Mongoose --- they will use User and Posts to model a one:many relationship
- examples located in 'the-web-developer-bootcamp/15_data_associations/references.js'
- now we will have users that look like this:
{
email:'asdas',
name: 'asdas',
posts: [
23578125876578, // a list of ids that correrspond to individual posts rather than having
256873456tg745, // the whole post in the array (i.e. referencing the post)
32fu4745974584,
45628yuuihrwte
]
}
{
id: 23578125876578,
title: 'asdas',
content: 'asdas'
}
Embed or Reference?
- can use either in almost all situations, but one usually lends itself better to what needs to
be done in the particular situation
Module.Exports
- will help clean up code and make it more modular