I would like to delete an object from a JSON objects array. Here is the schema
qualifications: {
Experience: [{
title: String,
companyName: String,
location: String,
years: Number
}],
Education:[ {
school: String,
years: Number,
}],
Licences: [String],
Honnors: [String],
}
For example how can I delete the object whose key is "school": "harvard university" ?
What i tried is
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$pull: {
qualifications: {
Education: {
school: "harvard university",
}
},
},
}
);
But unfortunatelly it doesn’t get deleted from the database. what is wrong?
2
Answers
qualifications
is an object, thus you can’t use the$pull
operator which requires an array field. Instead, you need the (.
) dot notation to update the nestedEducation
array:qualifications.Education
.Demo @ Mongo Playground
Updated
From your error message, it seems
qualifications
is an array instead of an object. Your schema should be as below:To remove the object from the nested arrays, the below query aims to remove all the objects with
school: "harvard university"
from theEducation
array, for the all objects in thequalifications
array,Demo (remove object from nested arrays) @ Mongo Playground
can you try: