【问题标题】:populate doesn't work for Mongoose always return undefinedpopulate 对 Mongoose 不起作用总是返回 undefined
【发布时间】: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 值。

标签: node.js mongodb mongoose


【解决方案1】:

首先你应该改变你的 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
      });
    });

它只会返回课程的标题。

【讨论】:

    猜你喜欢
    • 2013-11-23
    • 2021-07-19
    • 2019-05-29
    • 2014-03-24
    • 1970-01-01
    • 2013-12-17
    • 2015-08-16
    • 2020-08-24
    相关资源
    最近更新 更多