【问题标题】:Virtual populate with Mongoose使用 Mongoose 进行虚拟填充
【发布时间】:2020-12-08 12:24:23
【问题描述】:

我有以下 shema,如何从 Media 填充文档以获取教育、经验和认证?我尝试了很多方法,但都不起作用。

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

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    您可以使用路径属性进行深度链接,这也适用于数组类型。

    第 1 步: 将 documentId 字段的架构如下更改为 define 参考媒体收藏

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

    【讨论】:

    • 谢谢,但教育是一个数组。教育:[{标题:字符串,描述:字符串,年份:字符串,验证:布尔,documentId:mongoose.Schema.Types.ObjectId}]
    • 它也应该适用于数组类型。或者您可以尝试 const users = await User.find({}) .populate({ path: 'education.documentId' }) 而不使用虚拟,只需确保您在步骤 1 中定义架构
    【解决方案2】:

    查看populate

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

    【讨论】:

    • 感谢您的回答,但我需要按教育、经验或认证的 documentId 填充 Document。你有更多的解决方案吗? ==> 检查这个:documentId: mongoose.Schema.Types.ObjectId
    猜你喜欢
    • 2019-06-17
    • 2018-05-20
    • 2017-12-06
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 2017-09-19
    • 2018-03-10
    • 2018-10-20
    相关资源
    最近更新 更多