猫鼬:填充引用的子文档

时间:2018-08-01 00:07:20

标签: node.js mongodb express mongoose

我具有以下架构:

在CostCenter子文档能力中引用能力的事件。

const OccurrenceSchema = new mongoose.Schema({
  date: {
    type: Date,
    default: Date.now,
  },
  competence: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'CostCenter.competences',
  },
  ...
})

CostCenter,其中有一系列子文档,可以通过Occurence进行引用。

const CostCenterSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
  competences: [CompetenceSchema],
});

最后是能力。

const CompetenceSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
});

当我尝试填充权限时,出现“未为模型\“ CostCenter.competences \”注册架构。\ n使用mongoose.model(name,schema)“。

const occurrence_list = (request, response) => {
  Occurrence.find()
    .populate('occurrence origin tag entity method priority competence')
    .then(occurrences => response.send(occurrences))
    .catch(e => response.send(e));
};

在引用子文档时如何填充事件?

1 个答案:

答案 0 :(得分:1)

首先,您需要将发生模式更改为此

const OccurrenceSchema = new mongoose.Schema({
   date: { type: Date, default: Date.now },
   competence: { type: mongoose.Schema.Types.ObjectId, ref:'CostCenter' }
});
mongoose.model('Occurrence', OccurrenceSchema);

和CostCenter模型:

const CostCenterSchema = new mongoose.Schema({
   name: { type: String, required: true, trim: true },
   competences:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Competence' }],
});
mongoose.model('CostCenter', CostCenterSchema);

最终胜任力模型:

const CompetenceSchema = new mongoose.Schema({
   name: { type: String, required: true, trim: true }
});
mongoose.model('Competence', CompetenceSchema);

要从Occurrence填充能力,您可以这样做:

Occurrence.find({ your_query })
.populate('competence')
.then(occurrences => response.send(occurrences))
.catch(e => response.send(e));

希望有帮助!

相关问题