2013-11-21 39 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

相關問題