用猫鼬虚拟填充 [英] Virtual populate with Mongoose

查看:41
本文介绍了用猫鼬虚拟填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下shema,如何从Media中填充文档以进行教育,经验和认证?我已经尝试了很多方法,但是没有用.

I have the following shema, how to populate document from Media for education, experience, and certification? I have tried many ways but it does not work.

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 });
};

推荐答案

您可以使用path属性进行深层链接,这也适用于Array类型.

You can use the path attribute for deep linking, this would work for Array types too.

第1步:如下所示,将documentId字段的架构更改为定义参考

Step 1: Change the schema of documentId field as below to define reference to the 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()

这篇关于用猫鼬虚拟填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆