gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:29:01 26 4
gpt4 key购买 nike

架构定义

团队.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",
}

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

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

最佳答案

我也遇到过同样的问题。我已使用此代码进行救援:

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

关于node.js - Mongoose - 使用 .populate 访问嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24402764/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com