Как мне перечислить только учеников, которые относятся к классу?
**Student MongoDB**
id: ObjectId('5cafc39681d41e11ecccd042')
classroom:
Objectid:('5cafb1d9a36c8123f86b8e30')
fullName:"Student Jim"
__v:0
**Classroom MongoDB**
_id: ObjectId:('5cafb1d9a36c8123f86b8e30')
author: Objectid:('5ca405020a1fef3ed0a3dcb8')
createdAt:2019-04-11T21:30:01.004+00:00
classroomname:"Classroom 2"
__v:0
Теперь я попытался выполнить итерацию, поэтому я могу перечислить только учеников, принадлежащих к классу, на который я нажал, который открывается в http://localhost:8080/classroom/students/5cafb1d9a36c8123f86b8e30, который является идентификатором класса.
Вот как я пытался повторить:
extends layout
block content
for classroom in classrooms && student in students
if student.classroom.id == classroom.id
p= student.fullName
Я не уверен, что я на правильном пути, если я - я пропускаю только часть итерации.
Спасибо за помощь.
ОБНОВЛЕНИЕ С БОЛЕЕ КОДОМ
**Classroom.controller.js**
const express = require('express');
var router = express.Router();
var bodyParser = require('body-parser')
const mongoose = require('mongoose');
const passport = require('passport');
const ObjectId = mongoose.Types.ObjectId;
const Student = require('../models/student');
const Classroom = require('../models/classroom');
const passportConfig = require('../config/passport');
const app = express();
// Get classroom add page
router.get('/',passportConfig.isAuthenticated,(req, res) => {
res.render('classroom');
});
// Insert new classroom
router.post('/',(req, res) => {
InsertRecord(req, res);
});
// Update the classroom name
router.post('/update', (req, res) => {
updateRecord(req, res);
});
function updateRecord(req,res){
Classroom.findOneAndUpdate({ _id: req.body._id}, req.body, {new: true}, (err,doc)=> {
if (!err) { res.redirect('./names');}
else {
if (err.name == 'ValidationError'){
handleValidationError(err, req.body);
res.render('update', {
classroom: req.body
});
}
else
console.log('Error during update:' +err);
}
});
}
// Add new classroom to the database
function InsertRecord(req, res){
var classroom = new Classroom();
classroom.classroomname = req.body.classroomname;
classroom.author.id = req.user._id,
classroom.save((err, doc) => {
if (!err)
res.redirect('classroom/names');
else {
if (err.name == 'ValidationError') {
handleValidationError(err, req.body);
res.render('classroom/names', {
viewTitle: 'Insert Classroom',
classroom: req.body
});
}
else
console.log('Error during record insertion:' + err);
}
});
}
// List all the classrooms that belongs to the logged user
router.get('/names',passportConfig.isAuthenticated, (req, res) => {
Classroom.find((err, docs) => {
if (!err) {
res.render('names', {
classrooms:docs
});
}
else {
console.log('Error in retrieving students: '+ err);
}
});
});
router.get("/students/:classroomid", async (req, res) => {
const classId = mongoose.Types.ObjectId(req.params.classroomid)
const students = await Student.find({
classroom: classId
}, {
fullName: 1
})
res.render('studentsinclass', {
students: students
})
})
// Update classroom name by ID
router.get('/update/:id',passportConfig.isAuthenticated,(req, res) => {
Classroom.findById(req.params.id, (err, docs) => {
if (!err) {
res.render('update', {
viewTitle: 'Update',
classrooms: docs
});
}
});
});
// delete Classroom by ID
router.get('/delete/:id',passportConfig.isAuthenticated,(req, res) => {
Classroom.findByIdAndRemove(req.params.id, (err, docs) => {
if (!err) {
res.redirect('/classroom/names');
}
else {console.log('Error in classroom deletion:' +err);}
});
});
module.exports = router;
**Classroom Schema**
const mongoose = require('mongoose');
const classroomSchema = new mongoose.Schema({
classroomname: {
type: String
},
createdAt: { type: Date, default: Date.now },
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
},
students: {
id : {
type: mongoose.Schema.Types.ObjectId,
ref: "Student"
}
}
});
const Classroom = mongoose.model('Classroom', classroomSchema);
module.exports = Classroom;
**Students.controller.js**
const express = require('express');
var router = express.Router();
var bodyParser = require('body-parser')
const mongoose = require('mongoose');
const passport = require('passport');
const Student = require('../models/student');
const Classroom = require('../models/classroom');
const passportConfig = require('../config/passport');
const app = express();
// router.get('/',passportConfig.isAuthenticated,(req, res) => {
// res.render('students');
// });
router.get('/',passportConfig.isAuthenticated,(req, res) => {
Classroom.find((err, docs) => {
if (!err) {
res.render('students', {
classrooms: docs
});
}
});
});
router.post('/',(req, res) => {
InsertRecord(req, res);
});
function InsertRecord(req, res){
var student = new Student();
student.fullName = req.body.fullname;
student.classroom.id = req.body.studentclassroom;
student.save((err, doc) => {
if (!err)
res.redirect('students/list');
else {
console.log(' Error during insertion: '+ err);
}
});
}
router.get('/list',passportConfig.isAuthenticated, (req, res) => {
Student.find((err, docs) => {
if (!err) {
res.render('list', {
list:docs
});
}
else {
console.log('Error in retrieving students: '+ err);
}
});
});
module.exports = router;
**Students schema**
const mongoose = require('mongoose');
const studentSchema = new mongoose.Schema({
fullName: {
type: String
},
classroom: {
name: {
type: String
},
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "classroom",
}
},
});
const Student = mongoose.model('Student', studentSchema);
module.exports = Student;