Mongoose ile sanal nüfus

Aug 19 2020

Aşağıdaki şema var, eğitim, deneyim ve sertifika için Medyadan belge nasıl doldurulur? Birçok yol denedim ama işe yaramıyor.

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

Yanıtlar

AlpeshPatil Aug 26 2020 at 19:58

Derin bağlantı için path niteliğini kullanabilirsiniz, bu, Dizi türleri için de işe yarar.

Adım 1: Media Collection referansını tanımlamak için documentId alanının şemasını aşağıdaki gibi değiştirin

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

Adım 2: Şemadaki sanal özellikleri tanımlayın

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

3. Adım: Derin bağlantı için yol tanımıyla firavun faresi populate kullanın

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

çek doldurmak

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