For my project, I am utilizing mongoose to create a database. The schema for my Class
looks like this:
const mongoose = require('mongoose')
const classSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
consultant: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Consultant',
required: true
},
startYear: {
type: String,
required: true
},
classname: {
type: String,
required: true,
unique: true
},
studentList: [
{
code: {
type: String,
required: true
},
fullname: {
type: String,
required: true
}
}
]
})
const Class = mongoose.model('Class', classSchema)
module.exports = Class
The property studentList
is an array which is stored in mongoose Atlas as shown in the image below:
https://i.stack.imgur.com/Pf1WD.jpg
To delete a subdocument from the array studentList
, I have created a route:
http://localhost:5000/users/:code
This is the implementation:
exports.delele_student_from_user = (req, res, next) => {
var { code } = req.params;
var { classname } = req.body;
User.findOneAndDelete({
classname,
studentList: {
$pull: {
code,
},
},
})
.exec()
.then((doc) => {
console.log(`deleted user with code ${code} from collection User`);
next();
})
.catch((err) => {
console.log(err);
return res.status(500).json({ err });
});
};
However, when executing this code, I encountered the following Error:
{ MongoError: unknown operator: $pull ...
If anyone can assist me in resolving this issue, it would be greatly appreciated. Thank you and have a wonderful day!