Виртуальное заселение с помощью 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

Вы можете использовать атрибут path для глубокой ссылки, это также будет работать для типов массивов.

Шаг 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()
Tahero Aug 19 2020 at 10:49

проверить заполнить

const users = await User.find({}).populate('education').populate('experience').populate('certification')