수색…


통사론

  1. Model.Query.populate (경로, [선택], [모델], [일치], [옵션]);

매개 변수

Param 세부
통로 String - 채울 필드 키입니다.
고르다 Object, String - 모집단 쿼리의 필드 선택입니다.
모델 모델 - 참조 된 모델의 인스턴스
시합 Object - 조건을 채 웁니다.
옵션들 개체 - 쿼리 옵션

단순 채우기

몽구스 채우기는 다른 콜렉션에서 참조 된 문서의 데이터를 표시하는 데 사용됩니다.

Address 라는 문서를 참조한 Person 모델이 있다고 가정 해 보겠습니다.

사람 모델

var Person = mongoose.model('Person', {
    fname: String,
    mname: String,
    lname: String,
    address: {type: Schema.Types.ObjectId, ref: 'Address'}
});

주소 모델

var Address = mongoose.model('Address', {
    houseNum: String,
    street: String,
    city: String,
    state: String,
    country: String
});

findOne() 을 사용하여 ObjectId를 사용하여 Person 내에 Address 를 채우려면 populate populate() 함수를 사용하고 필드 키 address 를 첫 번째 매개 변수로 추가하십시오.

Person.findOne({_id: req.params.id})
    .populate('address') // <- use the populate() function
    .exec(function(err, person) {
        // do something.
        // variable `person` contains the final populated data
    });

또는

Person.findOne({_id: req.params.id}, function(err, person) {
    // do something
    // variable `person` contains the final populated data
})
.populate('address');

위의 쿼리는 아래 문서를 생성해야합니다.

사람 문서

{
    "_id":"123abc",
    "fname":"John",
    "mname":"Kennedy",
    "lname":"Doe",
    "address":"456def" // <- Address' Id
}

주소 문서

{
    "_id":"456def",
    "houseNum":"2",
    "street":"Street 2",
    "city":"City of the dead",
    "state":"AB",
    "country:"PH"
}

채워진 문서

 {
    "_id":"123abc",
    "fname":"John",
    "mname":"Kennedy",
    "lname":"Doe",
    "address":{
        "_id":"456def",
        "houseNum":"2",
        "street":"Street 2",
        "city":"City of the dead",
        "state":"AB",
        "country:"PH"
    }
}

몇 개의 필드 무시

마지막으로 채워진 doc의 address 필드에 fields houseNumstreet 필드를 사용 하지 않으려면 populate() 를 다음과 같이 사용한다고 가정 해 보겠습니다.

Person.findOne({_id: req.params.id})
    .populate('address', '-houseNum -street')  // note the `-` symbol
    .exec(function(err, person) {
        // do something.
        // variable `person` contains the final populated data
    });

또는

Person.findOne({_id: req.params.id}, function(err, person) {
    // do something
    // variable `person` contains the final populated data
})
.populate('address', '-houseNum -street');  // note the `-` symbol

그러면 다음과 같이 채워진 최종 문서가 생성됩니다.

채워진 문서

 {
    "_id":"123abc",
    "fname":"John",
    "mname":"Kennedy",
    "lname":"Doe",
    "address":{
        "_id":"456def",
        "city":"City of the dead",
        "state":"AB",
        "country:"PH"
    }
}

몇 개의 필드 만 채우기

마지막으로 채워진 doc의 address 필드에 houseNumstreet 필드 있으면 위의 두 가지 메소드에서 다음과 같이 populate() 함수를 사용하십시오.

Person.findOne({_id: req.params.id})
    .populate('address', 'houseNum street')
    .exec(function(err, person) {
        // do something.
        // variable `person` contains the final populated data
    });

또는

Person.findOne({_id: req.params.id}, function(err, person) {
    // do something
    // variable `person` contains the final populated data
})
.populate('address', 'houseNum street');

그러면 다음과 같이 채워진 최종 문서가 생성됩니다.

채워진 문서

 {
    "_id":"123abc",
    "fname":"John",
    "mname":"Kennedy",
    "lname":"Doe",
    "address":{
        "_id":"456def",
        "houseNum":"2",
        "street":"Street 2"
    }
}

중첩 인구

당신이 가지고 말할 수 user 가 들어 스키마, name , contactNo , address , 그리고 friends .

var UserSchema = new mongoose.Schema({
    name : String,
    contactNo : Number,
    address : String,
    friends :[{
        type: mongoose.Schema.Types.ObjectId,
        ref : User
    }]
});

당신이 친구 , 친구 , 친구들 을 찾고자한다면, 당신은 2 단계, 즉 중첩 된 인구 에 인구를 할 필요가 있습니다.

친구 및 친구의 친구를 찾으려면,

User.find({_id : userID})
    .populate({ 
        path : 'friends',
        populate : { path : 'friends'}//to find friends of friends
    });

populate 모든 parametersoptions 은 중첩 된 채우기에도 사용되어 원하는 결과를 얻을 수 있습니다.

마찬가지로 요구 사항에 따라 더 많은 levels populate 수 있습니다.

중첩 된 채우기를 3 단계 이상 수행하지 않는 것이 좋습니다. 3 단계 이상 중첩 된 채우기를 수행해야하는 경우 스키마를 재구성해야 할 수 있습니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow