Isi virtual dengan Mongoose

Aug 19 2020

Saya memiliki shema berikut, bagaimana cara mengisi dokumen dari Media untuk pendidikan, pengalaman, dan sertifikasi? Saya telah mencoba banyak cara tetapi tidak berhasil.

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

Jawaban

AlpeshPatil Aug 26 2020 at 19:58

Anda dapat menggunakan atribut path untuk deep linking, ini juga akan berfungsi untuk jenis Array.

Langkah 1: Ubah skema bidang documentId seperti di bawah ini untuk menentukan referensi ke Koleksi Media

documentId: { type: mongoose.ObjectId, ref: 'Media' },

Langkah 2: Tentukan properti virtual pada skema

schema.virtual('educationDocument', {   
    ref: 'Media', // the collection/model name
    localField: 'education.documentId',
    foreignField: '_id',
    justOne: true, // default is false });

Langkah 3: Gunakan mongoose populate dengan definisi jalur untuk tautan dalam

const users = await User.find({})
    .populate({ path: 'educationDocument' })
    .populate({ path: 'experienceDocument' })
    .populate({ path: 'certificationDocument' })
    .execPopulate()
Tahero Aug 19 2020 at 10:49

cek populate

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