目前有幻灯片和不同类型幻灯片的概念。我正在尝试使用设置为幻灯片类型的动态引用来填充幻灯片对象上的 slides
数组,以获取具有不同文档的幻灯片填充数组。
匹配 http://mongoosejs.com/docs/populate.html 处的文档在“动态引用”标题下,我的代码如下所示。
// Abreviated slideshow model
var slideshowSchema = mongoose.Schema({
slides: [{
slideType: String,
item: {
type: Schema.Types.ObjectId,
refPath: 'slides.slideType'
}
}]
}]
// controller get route
app.get('/slideshow/:id', function(req, res, next) {
var id = req.params.id;
if(id){
Slideshow
.findById(id)
.populate('slides.item')
.exec(function(err, slideshow) {
res.writeHead( 200, { "Content-Type": "application/json" } );
res.end(JSON.stringify(slideshow));
});
}
else{
return next();
}
});
// type of slide trying to be populated
var currentWeatherSchema = mongoose.Schema({
slideType: {
type: String,
required: true
},
slideshowId: {
type: Schema.Types.ObjectId,
required: true
}
// other unique props
});
当在硬编码的幻灯片类型上进行直接填充时,幻灯片按预期填充,并且当运行上面的代码时,我确实得到了响应,并且幻灯片数组填充了正确数量的对象,但它们看起来像这样而不是预期的文档:
"slides": [
{
"_bsontype": "ObjectID",
"id": {
"type": "Buffer",
"data": [
89,
126,
152,
150,
243,
157,
179,
147,
165,
23,
247,
56
]
}
}
]
我已经阅读了无数次这些例子,但无法弄清楚我哪里错了。有谁有这样做的经验,或者看看我可能缺少什么?
最佳答案
看起来您的填充正在返回存储的 ObjectId,因为未找到集合引用(如果找到并且对象不匹配,它将返回 null)。因此,集合文档中的“slideType”值没有有效的集合引用。
- 为每个架构创建一个模型。
- 使用模型创建时的名称填充幻灯片类型。请注意大写字母。
- 确保正确引用的 ObjectId 相同。
关于node.js - 使用 Mongoose Dynamic Populate 得到意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45407191/