On the frontend I compile a collection of bookmark ids to be deleted as seen in the following function:
public deleteBookmarks = (siteId) => {
const siteForBookmarkDelete = this.category?.sites.find(s1 => s1.site._id === siteId)
const bookmarksForDelete = siteForBookmarkDelete.site.bookmarks
.filter(bookmark => bookmark.checked === true)
const bookmarkIds = [];
for(let bm of bookmarksForDelete) {
bookmarkIds.push(bm._id)
}
this.categoriesService.deleteBookmark(this.category?._id, siteId, bookmarkIds )
}
On the backend, I tried to delete the bookmarks with the condition:
...
{
$pull: {
bookmarks: {
_id: {$in: bookmarkIds}
}
}
})
I get the error:
CastError: Cast to ObjectId failed for value "63bd8916abbd6f490b568121,63bd8918abbd6f490b56812a" (type string) at path "_id" because of "BSONTypeError"
at model.Query.exec
I interpret this to mean even though I put actual ObjectIds on the array, they were converted to strings so I modified my backend code to convert each _id on the array to ObjectId.
const mongoose = require('mongoose')
const { ObjectId} = mongoose.Schema.Types;
exports.deleteBookmarks = async (req, res) => {
const {categoryId, siteId, bookmarkIds} = req.params;
const objectIds = [ObjectId];
for(let bmId of bookmarkIds) {
objectIds.push(ObjectId(bmId))
}
try {
const site = await Sites.findOneAndUpdate({
_id: siteId,
categoryId
},
{
$pull: {
bookmarks: {
_id: {$in: objectIds}
}
}
})
getAllCategories(req, res);
} catch(error) {
console.error(error);
return res.status(500).send('Error adding bookmark.')
}
}
Then I get this error:
\node_modules\mongoose\lib\schematype.js:43
this[schemaTypeSymbol] = true; ^
TypeError: Cannot set properties of undefined (setting 'Symbol(mongoose#schemaType)')
at SchemaType
I am thinking this ObjectId may be the wrong one to use but the documentation doesn't show what package it is getting its ObjectId from.
const { ObjectId} = mongoose.Schema.Types;