使用node.js和mongoose填充另一个引用文档的数据
我正在构build一个运行课程的应用程序。 每门课程都有单位。 每个单元最后都有页面,问题和测验。 我以为我有一切正确的设置,但如果我查看单位列表,它只显示ID,并不填充。
楷模:
var unitSchema = new Schema({ number: Number, title: String, unitCode: String, pageCount: Number, time: Number }); var pageSchema = new Schema({ number: Number, title: String, content: String, courseQ: Boolean, unitCode: String }); var courseQuestionSchema = new Schema({ question: String, choices: [], correct: Number }); var quizSchema = new Schema({ code: String, questions: [{ question: String, choices: [], correct: Number }] }); var courseSchema = new Schema({ name: String, code: String, state: String, instructor: String, agency: String, providerNumber: String, schoolNumber: String, price: {type: Number, get: getPrice, set: setPrice }, available: Boolean, units : [{ type : Schema.ObjectId, ref : 'unitSchema' }], pages : [{ type : Schema.ObjectId, ref : 'pageSchema' }], cQuestions : [{ type : Schema.ObjectId, ref : 'courseQuestionSchema' }], quizzes : [{ type : Schema.ObjectId, ref : 'quizSchema' }] });
Schema.statics:
unitSchema.statics = { list: function (options, cb) { var criteria = options.criteria || {}; this.find(criteria) .populate('units') .exec(cb) } }
控制器:
exports.coursesUnits = function(req, res){ var options = { criteria: { 'id':req.param('units',req.course.units.id)} }; Courses.list(options, function(err, units) { if (err) return res.render('500'); res.render('admin/courses/units', { title: '', description: '', units: req.course.units, course: req.course, active: 'courses', active2: 'course-list', active3: '' }) }) };
我花了整整一周寻找解决这个问题,没有运气。 提前感谢任何指向正确方向的指针。
我为你感到难过。 我觉得你搞砸了你的模型。 属性'ref'只适用于其他模型,而不是模式。
你必须首先使用mongoose.model('Quiz',quizSchema)创build一个模型,
之后,您可以参考“测验”。
这样它会为测验创build一个新的集合,并使用objectId引用它。
这里是文档: http : //mongoosejs.com/docs/populate.html