Mongo DB - Related Models

From Logic Wiki
Jump to: navigation, search


Using References (Normalization)

Consistency

let author = { 
   name:'Ali'
}
let course = {
   author:'id' 
}

How it's defined in model

const Course = mongoose.model('Course', new mongoose.Schema({
   name:string
   author:{
      type:mongoose.Schema.Types.ObjectId,
      ref:'Author'
   } 
}));

Querying data (Population)

async function listCourses(){
   const courses = await Course
      .find()
      .populate('author')
      .select('name author');
   console.log(courses);
 }

in order to include only some of the fields of populated data

      .populate('author', 'name')

in order to exclude some of the fields of populated data

      .populate('author', 'name -_id')

Using Embedded Documents (Denormalization)

Performance

let course = {
   author:{
     name:'Ali'
   } 
}

https://www.udemy.com/nodejs-master-class/learn/v4/t/lecture/9993130?start=0

How it's defined in model

By giving the schema name :

const Course = mongoose.model('Course', new mongoose.Schema({
   name:string
   author: authorSchema
}));

Creating

async function createCourse(name, author){
  const course = new Course({
    name,
    author
});

createCourse('Node Course', new Author({ name:'Ali'}));

it saves as subdocuments and only updated by parent doc.

Update directly in DB

async function updateAuthor(courseId){
  const course = await Course.update({ _id: courseId }, {
     $set: {
       'author.name:'John Smith'
     }
   });
 }

updateAuthor('123123123');

Hybrid

it's good for snapshot of data in a given point of time

let author = {
   name : 'Ali'
   // other properties 
}
let course = {
   author: {
     id:'ref',
     name:'Ali'
    }
}

See Also : Mongo DB usage in Node