(몽고DB) Mongoose - populate
몽구스의 populate 메서드는 다른 SQL DB 의 Join 기능과 비슷한 역할을 수행한다.
즉, 어떤 A 개체가 B 개체를 참조하고 있을 때(ObjectId 로 참조가 가능), populate 메서드를 이용해 해당 ObjectId 값을 가진 B 개체의 값을 그대로 가져올 수 있다.
User 개체를 위와 같이 만들고,
Video 개체의 creator 에서 User 개체를 참조하고 있다.
req.params.id 에는 video의 ObjectId 가 담겨 있다.
어떤 video 하나를 찾고, 그 video의 creator(ObjectId)를 User 개체에서 찾아 data로 돌려주는 코드이다.

콘솔에 data를 찍어본 결과, Video 개체엔 creator 의 id 만 있었는데, populate 메서드를 이용해 두 개체를 합쳐주었다.
즉, 어떤 A 개체가 B 개체를 참조하고 있을 때(ObjectId 로 참조가 가능), populate 메서드를 이용해 해당 ObjectId 값을 가진 B 개체의 값을 그대로 가져올 수 있다.
const userSchema = new mongoose.Schema({ userName: String, password: String, email: String, imgUrl: String }); export default mongoose.model("User", userSchema);
User 개체를 위와 같이 만들고,
const videoSchema = new mongoose.Schema({ videoName: String, description: String, views: Number, fileUrl: String, creator: {type: mongoose.Schema.Types.ObjectId, ref: "User", required: true} }); export default mongoose.model("Video", videoSchema);
Video 개체의 creator 에서 User 개체를 참조하고 있다.
Video.findOne( {_id: req.params.id}).populate("creator").exec((err, data) => { console.log(data); })
req.params.id 에는 video의 ObjectId 가 담겨 있다.
어떤 video 하나를 찾고, 그 video의 creator(ObjectId)를 User 개체에서 찾아 data로 돌려주는 코드이다.
콘솔에 data를 찍어본 결과, Video 개체엔 creator 의 id 만 있었는데, populate 메서드를 이용해 두 개체를 합쳐주었다.
댓글
댓글 쓰기