본문 바로가기
TIL: Today I Learned

[TIL] 20201221 Data Relationships With Mongo

by 김알리 2020. 12. 21.

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.