https://github.com/leeyulgok/NodejsPracticeVersion4.git
populate(): 다른 컬렉션의 값을 현재 컬렉션에 쉽게 가져올 수 있게 해준다. Mongoose에서는 관계를 설정할 때 ObjectId를 사용하기에 이 ObjectId를 사용하여 컬렉션과 관계를 가진 다른 컬렉션의 값도 함께 가져올 때 쓴다.
예시
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const authorSchema = new Schema({
name: {
type: String,
required: true
},
age: {
type: Number
}
});
const bookSchema = new Schema({
title: {
type: String,
required: true
},
author: {
type: Schema.Types.ObjectId,
ref: 'Author'
}
});
const Author = mongoose.model('Author', authorSchema);
const Book = mongoose.model('Book', bookSchema);
const book = new Book({
title: 'Example Book',
author: 'AuthorObjectId'
});
Book.find().populate('author').exec(function(err, books) {
console.log(books);
});
_id
를 참조한다._id
를 참조한다. 마지막으로 populate() 메서드의 인자로 author 필드 이름이 전달되고 exec() 메서드를 실행하면 Book 모델의 모든 데이터와 해당 author 데이터가 반환된다.