Mongoose document.populate() 不起作用

dco*_*296 3 mongoose mongodb node.js mongoose-populate mongoose-schema

我正在使用一个非常简单的 Node/Mongo/Express 设置,并尝试填充引用的文档。考虑我的“课程”模式,其中包含“周”:

// 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);
Run Code Online (Sandbox Code Playgroud)

我特别想填充我的几周数组(尽管当我将模式更改为一周时,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);
Run Code Online (Sandbox Code Playgroud)

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

// 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);
    });
  };
};
Run Code Online (Sandbox Code Playgroud)

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

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

感谢您为让我的人民工作而提出的任何建议!

shi*_*kar 6

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

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);
      });
    };
Run Code Online (Sandbox Code Playgroud)

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

  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);
    });
  });
Run Code Online (Sandbox Code Playgroud)

###更新2:也许更干净,这有效:###

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" });
Run Code Online (Sandbox Code Playgroud)