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},
payments: [{type: Number, required: true}],
active: {type: Boolean, required: true}
}],
})
const Student = mongoose.model('Student', studentSchema, 'students')
module.exports = Student
In the batchInfo
array there should be different batch’s info.
I have a student document like this:
{
"_id": "6683591adb3c21133fd99e12",
"name": "John",
"batchInfo": [
{
"batch_id": "66834a6d4b221111587def7b",
"studentID": "252105",
"payments": [2000, 1000]
"active": false
},
{
"batch_id": "668353316c57406f16e14449",
"studentID": "252301",
"payments": [1000]
"active": true,
}
]
}
Now, I want to update the payments
array where active
is true
. So, I want a document like this after the query:
{
"_id": "6683591adb3c21133fd99e12",
"name": "John",
"batchInfo": [
{
"batch_id": "668353316c57406f16e14449",
"studentID": "252301",
"active": true,
"payments": [1000]
}
]
}
Now I want to push an element to the payments
array.
I have tried this express code:
const mongoose = require('mongoose')
const Student = require("./models/Student")
app.post('/update/:id', async function (req, res) {
try {
const student = await Student.aggregate([
{"$match": {"$and": [{_id: req.params.id}, {"batchInfo.active": true}]}},
{"$push": {"batchInfo.payments": 4000}}
])
res.send(student)
} catch (error) {
res.send(error)
}
})
After trying this code nothing happens according to my requirements. How to solve this problem?
1