Mongoose로 가상 채우기
Aug 19 2020
교육, 경험 및 인증을 위해 미디어에서 문서를 채우는 방법은 다음과 같습니다. 여러 가지 방법을 시도했지만 작동하지 않습니다.
const mongoose = require('mongoose');
exports.User = schema => {
schema.add({
username: {
type: String,
index: true
},
education: [
{
title: String,
description: String,
year: String,
verified: Boolean,
documentId: mongoose.Schema.Types.ObjectId
}
],
experience: [
{
title: String,
description: String,
year: String,
verified: Boolean,
documentId: mongoose.Schema.Types.ObjectId
}
],
certification: [
{
title: String,
description: String,
year: String,
verified: Boolean,
documentId: mongoose.Schema.Types.ObjectId
}
]
});
schema.set('toObject', { virtuals: true });
schema.set('toJSON', { virtuals: true });
};
답변
AlpeshPatil Aug 26 2020 at 19:58
딥 링크에 경로 속성을 사용할 수 있습니다. 이것은 배열 유형에서도 작동합니다.
1 단계 : Media Collection에 대한 참조 를 정의 하기 위해 아래와 같이 documentId 필드의 스키마를 변경합니다 .
documentId: { type: mongoose.ObjectId, ref: 'Media' },
2 단계 : 스키마에서 가상 속성 정의
schema.virtual('educationDocument', {
ref: 'Media', // the collection/model name
localField: 'education.documentId',
foreignField: '_id',
justOne: true, // default is false });
3 단계 : 딥 링킹을위한 경로 정의와 함께 mongoose 채우기 사용
const users = await User.find({})
.populate({ path: 'educationDocument' })
.populate({ path: 'experienceDocument' })
.populate({ path: 'certificationDocument' })
.execPopulate()
Tahero Aug 19 2020 at 10:49
채우기 확인
const users = await User.find({}).populate('education').populate('experience').populate('certification')