Closed tzou2024 closed 2 years ago
Can you post the schema for you model and where you're actually calling this function?
i put cat instead of clat
rubber ducked once again
just kidding user schema:
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
},
major:{
type: String,
enum: ["ME", "ECE", "EBio", "E:C", "E:D", "E:Robo", "E:Sust"]
},
classes: {
type: Array,
default: []
}
},{
timestamps: true,
strict: false
})
calling the function:
function removeClassfromUser(usr, clas){
console.log("got here")
console.log("usr.classes: ",usr.classes)
console.log(typeof usr.classes)
let copy = usr.classes.filter((clat) =>{
return clat.class != clas
})
console.log("filtered user: ", copy)
}
//=============================
//DELETE Route Delete Class
//=============================
router.delete("/:id", (req,res) =>{
const classId= req.params.id
Class.findByIdAndRemove(classId)
.then(classf =>{
User.find({})
.then(userlist =>{
//console.log(userlist)
userlist.forEach((user) =>{
//console.log(user, user.classes, classId)
user = removeClassfromUser(user, classId)
user.save()
console.log("SAVED USER: ", user)
})
})
.catch(err=>{
console.log("err removing class from users")
})
res.redirect('/catalogue')
})
.catch(err =>{
res.json(err)
})
})
What's the problem you're trying to solve?
Right now I have a user with a class so that their classes are structured like:
I am trying to go through and delete them if the class has been deleted but I can't iterate through this because javascript thinks that it's an object not an array
Post any code you think might be relevant (one fenced block per file)
my idea was to do something like:
But the type of usr.classes is object, not array
If you see an error message, post it here. If you don't, what unexpected behavior are you seeing?
What is your best guess as to the source of the problem?
Javacsript being weird
What things have you already tried to solve the problem?
I tried cloning it as a list by doing [...usr.classes] but I get an error there too
Paste a link to your repository here
https://github.com/tzou2024/GraduationPlanner