수색…


통사론

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

매개 변수

매개 변수 설명
통로 < Object, String > 채울 경로 또는 모든 매개 변수를 지정하는 객체
[고르다] < Object, String > 모집단 쿼리를위한 필드 선택 ( '-id' 를 사용하여 id 필드를 제외한 모든 것을 포함 할 수 있음)
[모델] < Model > 모집단에 사용할 모델입니다. 지정하지 않으면 채우기가 스키마의 ref 필드에있는 이름으로 모델을 조회합니다.
[시합] < Object > 모집단 조건
[옵션] < Object > 모집단 쿼리 옵션 (정렬 등)

간단한 몽구스 예제

.populate() 를 사용하면 현재 컬렉션이나 문서에있는 참조를 해당 컬렉션의 정보로 채울 수 있습니다. 앞의 내용은 혼란 스러울 지 모르지만 예제가 혼란을 해결하는 데 도움이 될 것이라고 생각합니다.

다음 코드는 User와 Post라는 두 개의 콜렉션을 생성합니다.

var mongoose = require('mongoose'),
  Schema = mongoose.Schema

var userSchema = Schema({
  name: String,
  age: Number,
  posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
});

var PostSchema = Schema({
  user: { type: Schema.Types.ObjectId, ref: 'User' },
  title: String,
  content: String
});

var User = mongoose.model('User', userSchema);
var Post = mongoose.model('Post', postSchema);

모든 사용자를 .find({}) 때 각 사용자의 게시물을 모두 채우고 싶다면 다음을 수행 할 수 있습니다.

User
  .find({})
  .populate('posts')
  .exec(function(err, users) {
    if(err) console.log(err);
    //this will log all of the users with each of their posts 
    else console.log(users);
  }) 


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