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

时间:2014-06-25 07:34:26

标签: node.js mongodb mongoose

架构定义

Team.js

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

Student.js

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

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

{
    "__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",   
}

这是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);
        }
    });
});

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

{ _id: 53aa434858f760900b3f2246,
  students
   [ { block : 1
       status: 'joined'
       _id: 53aa436b58f760900b3f2249 },
     { block : 1
       status: 'joined'
       _id: 53aa436b58f760900b3f2250 }]
}

预期的输出是:

  { _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
           } 
        }
     ]
    }

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

参考: Populate nested array in mongoose

4 个答案:

答案 0 :(得分:3)

以下是您想要的简化版本。

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

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

然后是“团队”集合:

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

您就是这样做的:

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

  });

它会给你结果:

{
    "_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
            }
        }
    ]
}

你真的不需要“异步”模块,但我只是“习惯”。它没有“阻止”,因此我认为它更好。

正如您所看到的,您初始.populate()调用没有做任何事情,因为它期望从数组输入“键入”外部集合中的_id值,这严格来说“并不是因为”钥匙“在”学生“上,而是包含”外键“。

我确实用recent answer here覆盖了这个,可能并不完全针对你的情况。您的搜索似乎没有找到正确的“相同答案”(尽管不完全正确),您可以从中获取参考。

答案 1 :(得分:1)

你正在思考它。让Mongoose为你做的工作。

{{1}}

这会将学生作为文件返回,而不仅仅是ids。

答案 2 :(得分:1)

我一直面临同样的问题。我使用此代码进行救援:

Team.findOne({_id: req.team._id})
.populate({ path: "students.student"})
.exec(function(err, team) {
       console.log(team);
});

答案 3 :(得分:0)

TL DR

struct VideoAnswerWrapper: UIViewControllerRepresentable {

    typealias UIViewControllerType = VideoAnswerViewController

上下文

从所有答案中读取内容后,我开始进行所有测试,Neil Lun's answer才为我工作。问题是它在通往地狱的道路上。因此,我略微打碎了头,将其“重构”为优雅的单线。

const team = await Team.findById(req.team._id)
  .populate("students");

team.students = await Student.populate(team.students, {path: "student"});

我最初的问题:

const foundPost = await Post.findById(req.params.id)
  .populate("comments")
  .populate("author");

foundPost.comments = await User.populate(foundPost.comments, {path: "author"}); 

我的模型基本上是怎样的:

{
  title: "Hello World",
  description: "lorem",
  author: {/* populated */},
  comments: [ // populated
    {text: "hi", author: {/* not populated */ }}
  ]
};

问题解决后的输出:

User = {
  author,
  password
};

Post = {
  title,
  description,
  author: {}, //ref User
  comments: [] // ref Comment
};

Comment = {
  text,
  author: {} // ref User
};