【发布时间】:2016-01-01 01:09:15
【问题描述】:
我正在尝试创建一个电子学习应用程序,这是我的架构,但是现在每当我尝试在 mongodb 中呈现用户的课程并且它显示特定用户正在拥有的课程时都会出现问题。
数据在数组中
"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
});
});
});
即使我已经将数据添加到用户的课程字段中,它也总是返回未定义。
【问题讨论】:
-
Populate 仅适用于引用模型的
_id值,但看起来您正在使用title值。