Node.js Mongoose:填充引用的子文档
我有以下模式: 引用成本中心子文档能力中的能力的事件Node.js Mongoose:填充引用的子文档,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我有以下模式: 引用成本中心子文档能力中的能力的事件 const OccurrenceSchema = new mongoose.Schema({ date: { type: Date, default: Date.now, }, competence: { type: mongoose.Schema.Types.ObjectId, ref: 'CostCenter.competences', }, ... }) 成本中心,其中我有一个子文档
const OccurrenceSchema = new mongoose.Schema({
date: {
type: Date,
default: Date.now,
},
competence: {
type: mongoose.Schema.Types.ObjectId,
ref: 'CostCenter.competences',
},
...
})
成本中心,其中我有一个子文档数组,可以通过事件引用
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.Competencies \“。\n使用mongoose.model(名称,模式)”
引用子文档时如何填充引用?首先,您需要将引用模型更改为此
const OccurrenceSchema = new mongoose.Schema({
date: { type: Date, default: Date.now },
competence: { type: mongoose.Schema.Types.ObjectId, ref:'CostCenter' }
});
mongoose.model('Occurrence', OccurrenceSchema);
成本中心模式:
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.find({ your_query })
.populate('competence')
.then(occurrences => response.send(occurrences))
.catch(e => response.send(e));
希望有帮助 但是通过这样做,我不再有一个competencies子文档,而是有一系列他们自己收集的competencies(objectId),对吗?有没有办法像我想的那样?提前谢谢。我不明白你想要实现什么。你能先试试看结果是否符合你的要求吗?如果没有,你能举例说明你想要什么吗?我已经测试过了,我相信这是我真正想要的。基本上,我希望成本中心具有一系列独特的能力。这些能力不需要存储在集合中,因此我将它们作为子文档。通过获取引用,我希望能够使用引用的名称填充引用。我是Mongo的新手,所以我很抱歉解释得不好,我可能做了错事,但我不完全确定。很高兴听到你这么想。如果你还有任何问题,请告诉我。如果你想了解更多关于MongoDB的信息,这是一个非常好的开始,请将我的答案标记为你的答案,这样我就可以得到一些分数:))我的意思是“不真的”,你能阅读我说的其余内容并告诉我你的想法吗?也许我试图做的不是最好的解决方案,而你的是让我知道。当然啦!:)
Occurrence.find({ your_query })
.populate('competence')
.then(occurrences => response.send(occurrences))
.catch(e => response.send(e));