I'm trying to remove an object from an array in a document using mongoose.
This is an example of an entry:
{
_id: "12345",
folder: {
name: "Folder1",
files: [
{
fileName: "File 1",
fileID: "6789",
folderID: "12345"
}
],
active: true
}
}
This is what I am currently doing to remove the file from the array. The Attachment.unlink is what removes the file from the gridfs filestore. That part of the code works. My object however will not remove from the array.
router.delete("/filesystem/:id", (req, res, next) => {
Attachment.unlink(req.params.id, (error, attachment) => {
if (!attachment) return res.status(404);
if (error) return next(error);
Folder.findByIdAndUpdate(
{
_id: req.body.folderID
},
{
$pull: {
"folder.files": {
$elemMatch: { fileID: req.params.id }
}
}
},
{ multi: true, safe: true },
(error, folder) => {
if (error) return next(error);
return res.status(200).json({
folder
});
}
);
});
});
I have also tried to use update rather than findByIdAndUpdate. How do I remove an object from the array where the fileID is 6789?
mongoose.Types.ObjectId(req.params.id)_ids? If so you could dofolder.files.id(fileId).remove(). See mongoosejs.com/docs/subdocs.html#removing-subdocs_ids it is all one schema$pull: { "folder.files": { fileID: req.params.id } }instead of $elemMatch?