【发布时间】:2018-05-02 09:16:16
【问题描述】:
我正在使用一个非常简单的 Node/Mongo/Express 设置并尝试填充引用的文档。考虑一下包含“周”的“课程”模式:
// define the schema for our user model
var courseSchema = mongoose.Schema({
teachers : { type: [String], required: true },
description : { type: String },
previous_course : { type: Schema.Types.ObjectId, ref: 'Course'},
next_course : { type: Schema.Types.ObjectId, ref: 'Course'},
weeks : { type: [Schema.Types.ObjectId], ref: 'Week'},
title : { type: String }
});
// create the model for Course and expose it to our app
module.exports = mongoose.model('Course', courseSchema);
我特别想填充我的周数组(尽管当我将架构更改为一周时,populate() 仍然不起作用)。
这是我一周的架构(课程有多个):
var weekSchema = mongoose.Schema({
ordinal_number : { type: Number, required: true },
description : { type: String },
course : { type: Schema.Types.ObjectId, ref: 'Course', required: true},
title : { type: String }
});
// create the model for Week and expose it to our app
module.exports = mongoose.model('Week', weekSchema);
这是我的控制器,我试图在其中填充课程内的周数数组。我已遵循此文档:
// Get a single course
exports.show = function(req, res) {
// look up the course for the given id
Course.findById(req.params.id, function (err, course) {
// error checks
if (err) { return res.status(500).json({ error: err }); }
if (!course) { return res.sendStatus(404); }
// my code works until here, I get a valid course which in my DB has weeks (I can confirm in my DB and I can console.log the referenced _id(s))
// populate the document, return it
course.populate('weeks', function(err, course){
// NOTE when this object is returned, the array of weeks is empty
return res.status(200).json(course);
});
};
};
我觉得奇怪的是,如果我从代码中删除 .populate() 部分,我会得到正确的 _id 数组。但是当我添加 .populate() 时,返回的数组突然为空。我很迷茫!
我也尝试过模型填充(来自:http://mongoosejs.com/docs/api.html#model_Model.populate),但我得到了相同的结果。
感谢任何建议让我的人口工作!
【问题讨论】:
-
Model.population 而不是 instance.population
标签: node.js mongodb mongoose mongoose-schema mongoose-populate