.populate()不起作用

时间:2017-07-31 00:42:29

标签: javascript node.js mongodb mongoose

我一直在努力工作几个小时,无法找到解决方案。

我正在使用

制作学校目录

学生模特:

var mongoose = require("mongoose");


var studentSchema = new mongoose.Schema(
    {
        name: String,
        courses: [
            {
                type: mongoose.Schema.Types.ObjectId,
                ref:  "Course"
            }
        ]
    });

module.exports = mongoose.model("Student", studentSchema);

和课程模型......

var mongoose = require(" mongoose");

var courseSchema = new mongoose.Schema (
    {
        name: String,
        student: [
            {
                id: 
                {
                    type: mongoose.Schema.Types.ObjectId,
                    ref: "Student"
                },
                name: String
            }
        ]
    }
);

module.exports = mongoose.model("Course", courseSchema);

当我在找到的学生上运行.populate时......它不会填充学生中的课程值......

app.get("/students/:id", function(req, res){
    Student.findById(req.params.id).populate("courses").exec(function(err, foundStudent){
        if(err){
            console.log(err);
        } else {
            console.log(foundStudent);
            res.render("students/show", {student: foundStudent});
        }
    });
});

console.log(foundStudent)将显示...

{ _id: 597e7a49c945ee13529d0871,
  name: 'Collin DeSoto',
  __v: 1,
  courses: [ { _id: 597e7a4dc945ee13529d0872 } ] }

填充后......有什么想法吗?

1 个答案:

答案 0 :(得分:0)

试试这种方式

User.find(match, function (err, users) {
 var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]

  var promise = User.populate(users, opts);
  promise.then(console.log).end();
})

并预先发布此链接link