簡體   English   中英

虛擬填充 Mongoose

[英]Virtual populate with Mongoose

我有以下 shema,如何從媒體填充文檔以進行教育、體驗和認證? 我嘗試了很多方法,但它不起作用。

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

檢查填充

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

您可以使用 path 屬性進行深度鏈接,這也適用於 Array 類型。

第 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 步:使用 mongoose填充深度鏈接的路徑定義

const users = await User.find({})
    .populate({ path: 'educationDocument' })
    .populate({ path: 'experienceDocument' })
    .populate({ path: 'certificationDocument' })
    .execPopulate()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM