2015-10-04 75 views
1

我正在尝试创建一个电子学习应用程序,这是我的模式,但是现在的问题是,现在只要我尝试在MongoDB中呈现用户的课程,并且它显示的课程是特定用户正在拥有。填充不适用于Mongoose总是返回undefined

的数据是数组

"courses" : [ "Learn how to be awesome", "Learn how to be a chef" ] 

两个模式

var UserSchema = Schema({ 
    email: String, 
    password: String, 
    courses: [{ type: Schema.Types.String, ref: 'Course'}], 
}); 

var CourseSchema = Schema({ 
    title: String, 
    owners: [{ type: Schema.Types.ObjectId, ref: 'User'}], 
    body: String, 
    teacher: { type: Schema.Types.String, ref: 'User'}, 

}); 

routes.js的 - 每当我试图填充用户的课程对象时,它总是返回undefined

router.get('/my-courses', isLoggedIn, function(req, res) { 

    User 
    .findById(req.user.id) 
    .populate('courses') 
    .exec(function(err, courses) { 
     console.log(courses); // always return undefined 
     res.render('course/student-courses', { 
     userCourses: courses 
     }); 
    }); 
}); 

即使我已将数据添加到用户的课程字段中,它总是返回未定义的。

+0

填充只适用于被引用模型的'_id'值,但它看起来像使用'title'值。 –

回答

2

首先,你应该改变你的UserSchema:

var UserSchema = Schema({ 
    email: String, 
    password: String, 
    courses: [{ type: Schema.Types.ObjectId, ref: 'Course'}], 
}); 

只能通过_id引用另一个模式。 也为CourseSchema内的老师做这个改变。

然后使用与区选择填充:

User 
    .findById(req.user.id) 
    .populate('courses', 'title') 
    .exec(function(err, courses) { 
     console.log(courses); // always return undefined 
     res.render('course/student-courses', { 
     userCourses: courses 
     }); 
    }); 

它将返回的课程只有标题。