我有以下shema,如何从Media填充文档以进行教育,经验和认证?我已经尝试了很多方法,但是没有用。
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 });
};
答案 0 :(得分:0)
检查populate
const users = await User.find({}).populate('education').populate('experience').populate('certification')
答案 1 :(得分:0)
您可以使用path属性进行深层链接,这也适用于Array类型。
步骤1:如下更改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:使用猫鼬填充路径定义进行深层链接
const users = await User.find({})
.populate({ path: 'educationDocument' })
.populate({ path: 'experienceDocument' })
.populate({ path: 'certificationDocument' })
.execPopulate()