본문 바로가기

express

How to manage of 1:N relationship? mongoose

https://mongoosejs.com/docs/tutorials/virtuals.html
recommand look this site slowly.

I wondered how models are related each other and how they work?

MongoDB is noSQL(: Not only SQL) so I needed to change the relationship of models. Because I just know RDBMS. RDBMS is sophisticate to defining models. but mongoDB is not that much.

1. In 1:N relationship,  only 'N' object has foreignkey. '1' object dont have any foreignkey

const PostSchema = new mongoose.Schema({
    title: String,
    description: String,
    createdAt: date.now(),
    // has foreignkey here
    user: {
    	type: mongoose.Schema.ObjectId,
        ref: 'User',
        required: true
      }
    });
    
const UserSchema = new mongoose.Schema({
    //User object doesnt has any reference
    naem: String,
    email: String
});

_It is all we need to modeling database.

I wanted to show all the posts of each user when I searched a user.

At this situation, we can use "virtual" field and "populate()" method

First, define virtual post field in UserSchema.

UserSchema.virtual('posts', {
  ref: 'Post',
  localField: '_id',
  forignField: 'bootcamp',
});

Second, populate virtual field

User.find({}).populate('posts')

It is all we need to do reference other collections.

'express' 카테고리의 다른 글

"Udemy" API by myself  (0) 2020.05.13
Udemy course spec/APIs  (0) 2020.05.13
The process error handling  (0) 2020.05.11
회원 가입  (0) 2020.05.03
express api 분석 1."dependencies"  (0) 2020.05.01