如何仅列出属于教室的学生?
**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打开,这是教室ID。
这是我尝试迭代的方式:
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;
如果你使用express
和pug
和mongoose
然后直接传递需要结果而不是两个循环查找方法
import mongoose from 'mongoose'
.....
app.get("/classroom/students/:classRoomId", async (req, res) => {
const classId = mongoose.Types.ObjectId(req.params.classRoomId)
const students = await Student.find({
classroom: classId
}, {
fullName: 1
})
res.render('index', {
students: students
})
})
index.pug
extends layout
block content
for student in students
p = student.fullName
在这里你可以直接使用学生变量。
随着Ashok的帮助和一些小的改动,我已经成功了。这是工作代码。
app.get("/classroom/students/:id", async (req, res) => {
const classId = mongoose.Types.ObjectId(req.params.id)
// console.log(classId);
const students = await Student.find({
'classroom.id': classId
})
res.render('studentsinclass',{
students:students})
})