2013-11-21 35 views
1

我在构建一个运行课程的应用程序。每门课程都有单位。每个单元最后都有页面,问题和测验。我以为我有一切正确的设置,但如果我查看单位列表,它只显示ID并不填充。使用node.js和mongoose填充另一个引用文档的数据

型号:

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: '' 
     }) 
    }) 
}; 

我花了整整一个星期寻找一个解决这个问题,没有运气。预先感谢任何指向正确方向的指针。

回答

1

我很抱歉。我认为你把你的模型搞砸了。属性'ref'只适用于其他模型,不适用于模式。

你必须箱模型首先使用mongoose.model(“测验”,quizSchema)

之后,你可以参考“测验”。

这样它就会为测验创建一个新的集合,并使用objectId引用它。

以下是文档:http://mongoosejs.com/docs/populate.html

相关问题