เติมเต็มเสมือนกับพังพอน
Aug 19 2020
ฉันมี Shema ต่อไปนี้วิธีการเติมเอกสารจากสื่อเพื่อการศึกษาประสบการณ์และการรับรอง ฉันลองมาหลายวิธีแล้ว แต่ไม่ได้ผล
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
คุณสามารถใช้แอตทริบิวต์ path สำหรับการลิงก์ในรายละเอียดซึ่งจะใช้ได้กับประเภท Array ด้วย
ขั้นตอนที่ 1:เปลี่ยนสคีมาของฟิลด์ documentId ด้านล่างเพื่อกำหนดการอ้างอิงไปยัง Media Collection
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:ใช้พังพอนเติมด้วยนิยามเส้นทางสำหรับการลิงก์ในรายละเอียด
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')