【问题标题】:Mongoose document.populate() is not working猫鼬 document.populate() 不工作
【发布时间】:2018-05-02 09:16:16
【问题描述】:

我正在使用一个非常简单的 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);

我特别想填充我的周数组(尽管当我将架构更改为一周时,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),但我得到了相同的结果。

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

【问题讨论】:

  • Model.population 而不是 instance.population

标签: node.js mongodb mongoose mongoose-schema mongoose-populate


【解决方案1】:

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

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" });

【讨论】:

  • 谢谢!我不知道为什么文档群体而不是模型群体似乎不起作用
  • 当然,您可以从 Model.population 进行填充,也可以检查更新的答案。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    在您的情况下,“课程”是实例,但您需要使用课程(模型)

    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);
       // });
    
      };
    

    【讨论】:

      猜你喜欢
      • 2018-07-22
      • 2017-05-26
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 2013-11-01
      • 2021-02-10
      相关资源
      最近更新 更多