I am creating a student management system. I am using nodejs, expressjs, ejs and mongoose.
Here is the code for Student model:
const mongoose = require('mongoose')
const studentSchema = mongoose.Schema({
name: {type: String, required: true},
batchInfo: [{
batch_id: {type: mongoose.Schema.Types.ObjectId, ref: "Batch", required: true},
studentID: {type: String, required: true, unique: true},
}],
})
const Student = mongoose.model('Student', studentSchema, 'students')
module.exports = Student
Here, in the batchInfo array there should be different batch’s info.
Here is the code for Batch model:
const mongoose = require('mongoose')
const batchSchema = mongoose.Schema({
academicYear: {type: Number, required: true},
})
const Batch = mongoose.model('Batch', batchSchema, 'batches')
module.exports = Batch
Here is the express code:
const router = require('express').Router()
const mongoose = require('mongoose')
const Batch = require("./models/Batch")
const Student = require("./models/Student")
app.post('/admission', async function (req, res) {
try {
const batch_id = new mongoose.Types.ObjectId(req.body.batch_id)
const batchRes = await Batch.aggregate([
{"$match": {"_id": batch_id},
{"$lookup": {
"from": "students",
"localField": "_id",
"foreignField": "batchInfo.batch_id",
"as": "students"
}}
])
const batch = batchRes[0]
var studentRolls = []
for(let i=0; i<batch.students.length; i++) {
for(let j=0; j<batch.students[i].batchInfo.length; j++) {
studentRolls.push((Number(batch.students[i].batchInfo[j].studentID)+1).toString().slice(4))
}
}
studentRolls.sort(function(a, b) {return b-a})
if(studentRolls.length == 0) {
var studentID = "01"
} else {
var studentID = studentRolls[0]
}
const name = req.body.name
const batchInfo = {
batch_id: batch_id,
studentID: studentID
}
const student = new Student({
name: name,
batchInfo: batchInfo
})
await student.save()
res.redirect('/')
} catch (error) {
res.send(error)
}
})
I am using this HTML form (ejs) to create student:
<form method="POST" action="/admission">
<div>
<select name="batch_id">
<option selected>Select Batch</option>
<% for(let i=0; i<batches.length; i++) { %>
<option value="<%= batches[i]._id %>"><%= batches[i].academicYear %></option>
<% } %>
</select>
<label>Select Batch</label>
</div>
<div class="form-floating mb-3">
<input type="text" name="name">
<label>Name</label>
</div>
<div>
<button type="submit">Admit Student</button>
</div>
</form>
When I create first student, it become succeed. But if I want to create another student, then this error occurs:
{
"index": 0,
"code": 11000,
"keyPattern": {
"studentID": 1
},
"keyValue": {
"studentID": null
}
}
I have tried many times, but the error occurs evertime. How to solve this problem?