'Remove all elements in string array Mongoose schema
I'm trying to remove all of strings that match occurrences in the array of 'interestedStudents' in a Mongoose schema.
My Mongoose schema looks like this:
// Create a schema.
const schema = new mongoose.Schema<Post>({
interestedStudents: {
type: [{
type: String,
unique: true
}],
required: false,
},
})
//Create model
export const PostModel = model<Post>('Post', schema);
I'm trying to remove by using:
await PostModel.updateMany({ interestedStudents: { $pullAll : [userId]}})
But I'm getting the following error:
"CastError: Cast to [string] failed for value "[ { '$pullAll': [ '62854109cf9a6db1fcf0393b' ] } ]" (type string) at path "interestedStudents.0" because of "CastError"\n at model.Query.exec
What am I doing wrong? Is my Schema set up wrong? Maybe it's not an array of string?
Solution 1:[1]
It was as easy as this for anyone else coming here:
const { modifiedCount } = await PostModel.updateMany({}, { $pull: { interestedStudents: userId } })
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mattias Törnqvist |
