populate访问猫鼬的嵌套对象

populate访问猫鼬的嵌套对象

本文介绍了用.populate访问猫鼬的嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模式定义

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

Student.js

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

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

How I can populate "student" to get output, as below:

团队

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

这是我用来通过Mongoose获取文档的JS:

This is JS I use to get the document using 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);
        }
    });
});

在控制台输出中,我得到以下信息:

In my console output I get the following:

{ _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.

Some one please help me where I am wrong. How should I make use of .populate, so that , I can get the entire student object and not only its id.

参考:在猫鼬中填充嵌套数组

推荐答案

这是您想要的内容的简化版本.

Here is a simplified version of what you want.

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

Basic data to set up, first the "students":

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

您确实不需要异步"模块,但是我只是习惯"了.它不会阻止",因此我认为更好.

You really do not need the "async" module, but I am just "in the habit" as it were. It doesn't "block" so therefore I consider it better.

因此,如您所见,您最初的.populate()调用不会执行任何操作,因为它期望从外部输入中的_id值中键"出数组输入,而这个严格地说"并非如此因为键"位于包含外键"的学生"上.

So as you can see, you initial .populate() call does not do anything as it expects to "key" off of an _id value in the foreign collection from an array input which this "strictly speaking" is not so as the "key" is on "student" containing the "foreign key".

我确实在此处的最新答案中对此做了介绍,也许并非完全针对您的情况.看来您的搜索没有找到正确的相同答案"(尽管不完全正确),无法为您提供参考.

I really did cover this in a recent answer here, maybe not exactly specific to your situation. It seems that your search did not turn up the correct "same answer" ( though not exactly ) for you to draw reference from.

这篇关于用.populate访问猫鼬的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 04:12