如何解决用猫鼬虚拟填充
我有以下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,certification: [
{
title: String,documentId: mongoose.Schema.Types.ObjectId
}
]
});
schema.set('toObject',{ virtuals: true });
schema.set('toJSON',{ virtuals: true });
};
解决方法
检查populate
const users = await User.find({}).populate('education').populate('experience').populate('certification')
,
您可以使用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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。