가장 간단한 방법으로 몽구스 "채우기()"| Mongodb의 다른 스키마로 컬렉션을 가져오는 방법

안녕하세요 여러분, 저는 Mongodb/Mongoose의 혼란스러운 주제인 "Populate( )"기능에 대해 설명하고 설명하겠습니다.

문제 설명 :



다음과 같은 2개의 스키마 모델이 있다고 가정합니다.
1 - 주소 모델
2 - 사용자 모델

주소 모델:
여기에는 핀코드, 상태, 주소 등 3가지 속성이 있습니다.

const  mongoose = require("mongoose");
const  Schema = mongoose.Schema;

const  addressSchema = new  Schema({
    address:  String,
    state:  String,
    pincode : Number
});

const  Address= mongoose.model("address", addressSchema);
module.exports = Address;


사용자 모델:
여기에는 이름, 주소 및 명칭의 3가지 속성이 있습니다.

const  mongoose = require("mongoose");
const  Schema = mongoose.Schema;
const {ObjectId} = mongoose.Schema; 

const  userSchema = new  Schema({
    name:  String,
    designation:  String,
    address: {
        type :  ObjectId,
        ref :  "address"
    }
});

const  User = mongoose.model("user", userSchema);
module.exports = User;


해결책 :



사용자 모델에서 수정 사항을 볼 수 있습니까?
추가:

address: {
        type :  ObjectId,
        ref :  "address"
    }


여기에서 모든 변경을 수행합니다.

여기서는 User Model의 주소 섹션에 항목을 만드는 것이 아니라 주소 모델을 사용하여 데이터를 저장하고 User Model에서 __id_를 사용합니다.

그리고 사용자 모델에서 데이터를 가져올 때 주소 모델에서 주소 속성을 팝합니다.

개체 ID는 무엇입니까?




const {ObjectId} = mongoose.Schema; 


그리고

type :  ObjectId,


ObjectId는 Mongoose의 데이터 유형 중 하나이며 MongoDb 데이터베이스의 다른 컬렉션을 참조한다는 것을 몽구스에게 알려줍니다.

가져온 후에는 ref와 함께 사용됩니다.

심판이란 무엇입니까?



이제 ObjectId는 ref와 함께 사용됩니다.
Ref는 가져온 데이터가 있는 컬렉션을 Mongoose에 알려줍니다. 우리의 경우 사용자 모델에서 가져와서 사용하는 것은 주소 모델_입니다. 그래서,

address: {
        type :  ObjectId,
        ref :  "address"
    }


참고: ref의 값은

const  Address= mongoose.model("address", addressSchema);


주소 모델_에서.

마침내 POPULATE( )를 사용하여



이제 User Model에서 데이터를 가져와 가져올 때 User Model의 주소 속성을 Address Model의 데이터로 채울 차례입니다.

가정하자,
주소 모델에 있는 데이터의 __id_는 100입니다.
따라서 User Model에 데이터를 입력할 때 User Model의 address 속성에 __id_ 즉 100을 전달합니다.

User.find({}).populate("address").exec((err, result) => {
    if(err){
        return  res.json({error :  err})
    }
    res.json({result :  result})
    });




.populate("address")는 User.find({})에서 오는 데이터를 채우고 존재하는 __id_(이 경우 __id_는 100)를 찾은 다음 주소 모델에서 찾아 해당 데이터를 가져와 사용자 모델에 채웁니다. .

감사합니다



인내심을 갖고 끝까지 읽어 주셔서 감사합니다. 도움이 되셨기를 바랍니다. 🙂🙂🙂

내 포트폴리오: https://anujportfolio.herokuapp.com/
내 Github: https://github.com/singhanuj620
내 링크드인:

피드백은 언제나 환영합니다. 🤗🤗

좋은 웹페이지 즐겨찾기