Mongoose - 使用.populate访问嵌套对象

sab*_*ari 5 mongoose mongodb node.js

模式定义

Team.js

var TeamSchema = new Schema({
    // Team Name.
    name: String,
    lead: String,
    students :type: [{
      block : Number,
      status : String,
      student : {
        type: Schema.ObjectId,
        ref: 'Student'
    }]
});
Run Code Online (Sandbox Code Playgroud)

Student.js

var StudentSchema = new Schema({
   name: String,
   rollNo : Number,
   class : Number
});
Run Code Online (Sandbox Code Playgroud)

如何填充"学生"以获得输出,如下所示:

球队

{
    "__v": 1,
    "_id": "5252875356f64d6d28000001",
    "students": [
        {
            "__v": 1,
            "_id": "5252875a56f64d6d28000002",
             block : 1,
             status : joined,
            "student": {
                "name": Sumeeth
                "rollNo" : 2
                "class" : 5
            }
        },
        {
            "__v": 1,
            "_id": "5252875a56f64d6d28000003",
            block : 1,
            status : joined,
            "student": {
                "name": Sabari
                "rollNo" : 3
                "class" : 4
            }
        }
    ],
    "lead": "Ratha",   
}
Run Code Online (Sandbox Code Playgroud)

这是JS我用来使用Mongoose获取文档:

Team.findOne({
    _id: req.team._id
})            
.populate('students')
.select('students')
.exec(function(err, team) {
    console.log(team);
    var options = {
        path: 'students.student',
        model: 'Student'
    };
    Student.populate(team.students,options,function(err, students) {
        console.log(students);
        if (err) {
            console.log(students);
            res.send(500, {
                message: 'Unable to query the team!'
            });
        } else {
            res.send(200, students);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

在我的控制台输出中,我得到以下内容:

{ _id: 53aa434858f760900b3f2246,
  students
   [ { block : 1
       status: 'joined'
       _id: 53aa436b58f760900b3f2249 },
     { block : 1
       status: 'joined'
       _id: 53aa436b58f760900b3f2250 }]
}
Run Code Online (Sandbox Code Playgroud)

而预期的产出是:

  { _id: 53aa434858f760900b3f2246,
      students
       [ { block : 1
           status: 'joined'
           student :{
              "name": Sumeeth
              "rollNo" : 2
              "class" : 5
           } 
         },
         { block : 1
           status: 'joined'
           student :{
               "name": Sabari
              "rollNo" : 3
              "class" : 4
           } 
        }
     ]
    }
Run Code Online (Sandbox Code Playgroud)

有人请在我错的地方帮助我.我应该如何使用.populate,这样,我可以得到整个学生对象,而不仅仅是它的id.

参考: 在mongoose中填充嵌套数组

Nei*_*unn 3

这是您想要的简化版本。

基本数据要设置,首先是“学生”:

{ 
   "_id" : ObjectId("53aa90c83ad07196636e175f"), 
   "name" : "Bill",
   "rollNo" : 1,
   "class" : 12 
},
{ 
    "_id" : ObjectId("53aa90e93ad07196636e1761"),
    "name" : "Ted",
    "rollNo" : 2,
    "class" : 12
}
Run Code Online (Sandbox Code Playgroud)

然后是“团队”集合:

{ 
    "_id" : ObjectId("53aa91b63ad07196636e1762"),
    "name" : "team1",
    "lead" : "me",
    "students" : [ 
        { 
            "block" : 1,
            "status" : "Y",
            "student" : ObjectId("53aa90c83ad07196636e175f")
        },
        { 
            "block" : 2,
            "status" : "N",
            "student" : ObjectId("53aa90e93ad07196636e1761")
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

您可以这样做:

var async = require('async'),
    mongoose = require('mongoose');
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/team');

var teamSchema = new Schema({
  name: String,
  lead: String,
  students: [{
    block: Number,
    status: String,
    student: {
      type: Schema.ObjectId, ref: 'Student'
    }
  }]
});

var studentSchema = new Schema({
  name: String,
  rollNo: Number,
  class: Number
});

var Team = mongoose.model( "Team", teamSchema );
var Student = mongoose.model( "Student", studentSchema );

Team.findById("53aa91b63ad07196636e1762")
  .select('students')
  .exec(function(err, team) {
    console.log( team );

    async.forEach(team.students, function(student,callback) {
      Student.populate(
        student,
        { "path": "student" },
        function(err,output) {
          if (err) throw err;
          callback();
        }
      );
    },function(err) {
      console.log( JSON.stringify( team, undefined, 4 ) );
    });

  });
Run Code Online (Sandbox Code Playgroud)

它给你结果:

{
    "_id": "53aa91b63ad07196636e1762",
    "students": [
        {
            "block": 1,
            "status": "Y",
            "student": {
                "_id": "53aa90c83ad07196636e175f",
                "name": "Bill",
                "rollNo": 1,
                "class": 12
            }
        },
        {
            "block": 2,
            "status": "N",
            "student": {
                "_id": "53aa90e93ad07196636e1761",
                "name": "Ted",
                "rollNo": 2,
                "class": 12
            }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

你确实不需要“异步”模块,但我只是“习惯”。它不会“阻塞”,因此我认为它更好。

因此,正如您所看到的,您最初的.populate()调用不会执行任何操作,因为它期望_id从数组输入中“键”出外部集合中的值,而“严格来说”并不是这样,因为“键”位于“student” ” 包含“外键”。

我确实在最近的回答中对此进行了介绍,也许并不完全针对您的情况。看来您的搜索没有找到正确的“相同答案”(尽管不完全)供您参考。