猫鼬 document.populate() 不工作

Mongoose document.populate() is not working

我正在使用一个非常简单的 Node/Mongo/Express 设置并尝试填充参考文档。考虑我的 "Courses" 架构,其中包含 "Weeks":

// define the schema for our user model
var courseSchema = mongoose.Schema({

    teachers        : { type: [String], required: true  },
    description     : { type: String              },
    previous_course : { type: Schema.Types.ObjectId, ref: 'Course'},
    next_course     : { type: Schema.Types.ObjectId, ref: 'Course'},
    weeks           : { type: [Schema.Types.ObjectId], ref: 'Week'},
    title           : { type: String              }

});

// create the model for Course and expose it to our app
module.exports = mongoose.model('Course', courseSchema);

我特别想填充我的周数组(尽管当我将架构更改为一周时,populate() 仍然不起作用)。

这是我一周的模式(一个课程有多个):

var weekSchema = mongoose.Schema({

    ordinal_number  : { type: Number, required: true },
    description     : { type: String              },
    course          : { type: Schema.Types.ObjectId, ref: 'Course', required: true},
    title           : { type: String              }

});

// create the model for Week and expose it to our app
module.exports = mongoose.model('Week', weekSchema);

这是我的控制器,我试图在其中填充课程内的周数组。我已遵循此文档:

// Get a single course
exports.show = function(req, res) {

  // look up the course for the given id
  Course.findById(req.params.id, function (err, course) {

    // error checks
    if (err) { return res.status(500).json({ error: err }); }
    if (!course) { return res.sendStatus(404); }

    // my code works until here, I get a valid course which in my DB has weeks (I can confirm in my DB and I can console.log the referenced _id(s))

    // populate the document, return it
    course.populate('weeks', function(err, course){
      // NOTE when this object is returned, the array of weeks is empty
      return res.status(200).json(course);
    });
  };
};

我觉得很奇怪,如果我从代码中删除 .populate() 部分,我会得到正确的 _id 数组。但是当我添加 .populate() 时,返回的数组突然为空。我很困扰!

我也试过模型人口(来自:http://mongoosejs.com/docs/api.html#model_Model.populate)但我得到了相同的结果。

感谢您提供任何让我的人口工作的建议!

下面应该 return 带有填充周数组的课程

exports.show = function(req, res) {
      // look up the course for the given id
      Course.findById(req.params.id)
      .populate({
        path:"weeks",
        model:"Week"
      })
      .exec(function (err, course) {
            console.log(course);
      });
    };

###更新:你也可以从实例中填充###

  Course.findById(req.params.id, function (err, course) {
    // error checks
    if (err) { return res.status(500).json({ error: err }); }
    if (!course) { return res.sendStatus(404); }
    // populate the document, return it
    Course.populate(course,  { path:"weeks", model:"Weeks" }, function(err, course){
      console.log(course);
    });
  });

### Update2:也许更干净,这有效:###

Course.findById(req.params.id, function (err, course) {
    // error checks
    if (err) { return res.status(500).json({ error: err }); }
    if (!course) { return res.sendStatus(404); }
    // populate the document, return it
      console.log(course);
  }).populate(course,  { path:"weeks", model:"Weeks" });

这里您似乎使用的是 course.populate() 而不是 Course.populate()

用这个代码代替你的,我只把一个单词 course.populate() 改成了 Course.populate()

在你的情况下 "course" 是实例,但你需要使用 Course(Model)

Course.findById(req.params.id, function (err, course) {

    if (err) { return res.status(500).json({ error: err }); }
    if (!course) { return res.sendStatus(404); }

   // Guys in some case below three-line does not work in that case you must comment these lines and uncomments the last three-line

    Course.populate('weeks', function(err, course){
      return res.status(200).json(course);
    });

   // Course.populate({  path:"weeks", model:"Weeks" }, function(err, course){
   //   return res.status(200).json(course);
   // });

  };