我的架构:
var schoolSchema = new mongoose.Schema({
name: String,
classes:[
{
c_name:String,
c_strn:String,
students:[
{s_name:String,
s_roll:String,
s_address:String
}
]
}
],
});
var school = mongoose.model('school',schoolSchema);
示例文档:
var sainik = new school({name:'sain',
classes:
[
{
c_name:'1(one)',
c_strn:'100',
students:[
{
s_name:"Leo",
s_roll:"17",
s_address:"strt24",
},
{
s_name:"Kyle",
s_roll:"18",
s_address:"strt24",
}
]//array of students
}
]//array of classes
});
sainik.save().then(()=>console.log("Save it"));
代码:
app.get('/home/:id/:cid',function(req, res){
school.find().exec(function(err,data){
if (err){
console.log(err);
}
else{
console.log(data);
res.render("classDet",{data:data});
}
})
});
这里我需要知道如何使用类(class) ID 访问各个类(class)以及如何将学生数组打印为“classDet”中的列表 基本上,我正在创建一个学校管理系统,其中有很多类(class),类(class)内有学生列表。 我想仅当父类可以访问时才打印每个类(class)的所有学生。
最佳答案
您可以尝试以下任一方法:
app.get('/home/:id/:cid', function (req, res) {
school.find({ id: id, 'classes.c_id': cid }, { _id: 0, 'classes.c_id.$.students': 1 }).lean().exec(function (err, data) {
if (err) {
console.log(err);
}
else {
console.log(data);
res.render("classDet", { data: data });
}
})
})
app.get('/home/:id/:cid', function (req, res) {
school.aggregate([{ $match: { id: id } }, { $unwind: '$classes' }, { $match: { 'classes.c_id': cid } }, { $project: { _id: 0, students: '$classes.students' } }]).exec(function (err, data) {
if (err) {
console.log(err);
}
else {
console.log(data);
res.render("classDet", { data: data });
}
})
})
注意:两个结果都会略有不同,您可以测试它并从中选择一个,另请记住,如果请求中的id
正在数据库中搜索_id
,那么您需要在查询中使用它之前将id
字符串转换为ObjectId()
。此外,我们还在 .find()
中使用 .lean()
将 mongoose 文档转换为 Js 对象,以便在代码中处理数据时访问数据中的键。
关于node.js - 如何使用 Moongoose 访问整个子文档(对象数组中的对象数组)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60336941/