首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongoose:填充引用的SubDocument

Mongoose:填充引用的SubDocument
EN

Stack Overflow用户
提问于 2018-08-01 08:07:20
回答 1查看 135关注 0票数 0

我有以下模式:

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

代码语言:javascript
复制
const OccurrenceSchema = new mongoose.Schema({
  date: {
    type: Date,
    default: Date.now,
  },
  competence: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'CostCenter.competences',
  },
  ...
})

CostCenter,其中有一个可以按事件引用子文档数组。

代码语言:javascript
复制
const CostCenterSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
  competences: [CompetenceSchema],
});

最后是能力。

代码语言:javascript
复制
const CompetenceSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
});

当我尝试填充能力时,我得到“模式尚未为模型注册\"CostCenter.competences\".\nUse mongoose.model(name,schema)”。

代码语言:javascript
复制
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));
};

在引用子文档时,如何填充匹配项?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-01 08:27:00

首先,您需要将您的事件模型更改为

代码语言:javascript
复制
const OccurrenceSchema = new mongoose.Schema({
   date: { type: Date, default: Date.now },
   competence: { type: mongoose.Schema.Types.ObjectId, ref:'CostCenter' }
});
mongoose.model('Occurrence', OccurrenceSchema);

和CostCenter模型:

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

最后,能力模型:

代码语言:javascript
复制
const CompetenceSchema = new mongoose.Schema({
   name: { type: String, required: true, trim: true }
});
mongoose.model('Competence', CompetenceSchema);

要根据事件填写能力,您可以执行以下操作:

代码语言:javascript
复制
Occurrence.find({ your_query })
.populate('competence')
.then(occurrences => response.send(occurrences))
.catch(e => response.send(e));

希望它能帮上忙!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51623653

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档