【问题标题】:mongoose - populate sub-schema sub-array猫鼬 - 填充子模式子阵列
【发布时间】:2017-05-22 02:34:14
【问题描述】:

我正在尝试填充子架构字段。

一个项目包含多个ProjectFilters。 每个 ProjectFilter 引用一个 FilterValueFilterValue 包含在一个(并且只有一个)Filter 中。

项目架构

const ProjectSchema = new Schema({
  title: String,
  filters: [ProjectFilter.schema],
}, {
  timestamps: true,
  toJSON: {
    virtuals: true,
  },
});

ProjectFilterSchema

const ProjectFilterSchema = new Schema({
  filterValue: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'FilterValue',
  },
  isMain: {
    type: Boolean,
    default: false,
  },
}, {
  toJSON: {
    virtuals: true,
  },
});

FilterSchema

const FilterSchema = new Schema({
  label: String,
  values: [FilterValue.schema],
}, {
  timestamps: true,
  toJSON: {
    virtuals: true
  },
});

FilterValueSchema

const FilterValueSchema = new Schema({
  label: String,
  color: String,
}, {
  toJSON: {
    virtuals: true,
  },
});

此查询无效。 filterValue 是null:

let query = Project.findById(req.params.projectId, { _id: 0, filters: 1 });
query.populate('filters.filterValue');

我尝试使用虚拟填充:

ProjectFilterSchema.virtual('usedValue', {
  ref: 'Filter',
  localField: 'filterValue',
  foreignField: 'values._id',
  justOne : true,
});

但这会返回整个 Filter 文档,而不仅仅是所需的 FilterValue

【问题讨论】:

    标签: mongoose populate


    【解决方案1】:

    为了填充子文档,首先您需要明确定义 ID 引用的文档集合。 这样,猫鼬就会知道要查询哪个集合。

    (在 Mongoose 4 中,您可以跨多个级别填充文档)

    //ES6 syntax
    import mongoose from 'mongoose';
    
    const Schema = mongoose.Schema;
    const ObjectId = Schema.Types.ObjectId;
    
    const FilterSchema = new Schema({
       label: String,
       filtervalues: [FilterValueSchema],
    }, { collection: 'filter' })
    
    const FilterValueSchema = new Schema({
       label: String,
       color: String,
    }, { collection: 'filtervalue' })
    
    const ProjectFilterSchema = new Schema({
       filterValue: {
       type: ObjectId,
       ref: 'filtervalue',
    }, { collection: 'projectfilter' })
    
    mongoose.model('filters', ProjectFilterSchema);
    mongoose.model('projectfilter', ProjectFilterSchema);
    mongoose.model('filtervalue', FilterValueSchema);
    
    Project.findById(req.params.projectId, { _id: 0 })
      .populate('filters.filter.filterValue').
    

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 2013-06-20
      • 2016-08-17
      • 2017-05-07
      • 2017-09-13
      • 2012-10-16
      • 2015-11-27
      • 2015-07-28
      相关资源
      最近更新 更多