マングースを仮想的に取り込む

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')