Cư trú ảo với Mongoose

Aug 19 2020

Tôi có thông tin sau, làm cách nào để điền tài liệu từ Media cho giáo dục, kinh nghiệm và chứng nhận? Tôi đã thử nhiều cách nhưng không hiệu quả.

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

Trả lời

AlpeshPatil Aug 26 2020 at 19:58

Bạn có thể sử dụng thuộc tính đường dẫn để liên kết sâu, điều này cũng sẽ hoạt động đối với các loại Mảng.

Bước 1: Thay đổi lược đồ của trường documentId như bên dưới để xác định tham chiếu đến Bộ sưu tập phương tiện

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

Bước 2: Xác định thuộc tính ảo trên lược đồ

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

Bước 3: Sử dụng mongoose điền với định nghĩa đường dẫn để liên kết sâu

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

kiểm tra dân cư

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