mongoose - 填充子模式子数组

时间:2017-03-13 11:30:34

标签: mongoose populate

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

项目包含多个 ProjectFilters 。 每个 ProjectFilter 都会引用一个 FilterValue FilterValue 包含在一个(仅限一个)过滤器中。

ProjectSchema

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

但这会返回整个过滤器文档,而不仅仅是 FilterValue

1 个答案:

答案 0 :(得分:3)

为了填充子文档,首先需要显式定义ID引用的文档集合。 这样,mongoose将知道要查询的集合。

(在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').