mongodb/action/gridfs/delete.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
use bson::{doc, Bson};
#[cfg(docsrs)]
use crate::gridfs::FilesCollectionDocument;
use crate::{
action::action_impl,
error::{ErrorKind, GridFsErrorKind, GridFsFileIdentifier, Result},
gridfs::GridFsBucket,
};
impl GridFsBucket {
/// Deletes the [`FilesCollectionDocument`] with the given `id` and its associated chunks from
/// this bucket. This method returns an error if the `id` does not match any files in the
/// bucket.
///
/// `await` will return [`Result<()>`].
pub fn delete(&self, id: Bson) -> Delete {
Delete { bucket: self, id }
}
}
#[cfg(feature = "sync")]
impl crate::sync::gridfs::GridFsBucket {
/// Deletes the [`FilesCollectionDocument`] with the given `id` and its associated chunks from
/// this bucket. This method returns an error if the `id` does not match any files in the
/// bucket.
///
/// [`run`](Delete::run) will return [`Result<()>`].
pub fn delete(&self, id: Bson) -> Delete {
self.async_bucket.delete(id)
}
}
/// Deletes a specific [`FilesCollectionDocument`] and its associated chunks. Construct with
/// [`GridFsBucket::delete`].
#[must_use]
pub struct Delete<'a> {
bucket: &'a GridFsBucket,
id: Bson,
}
#[action_impl]
impl<'a> Action for Delete<'a> {
type Future = DeleteFuture;
async fn execute(self) -> Result<()> {
let delete_result = self
.bucket
.files()
.delete_one(doc! { "_id": self.id.clone() })
.await?;
// Delete chunks regardless of whether a file was found. This will remove any possibly
// orphaned chunks.
self.bucket
.chunks()
.delete_many(doc! { "files_id": self.id.clone() })
.await?;
if delete_result.deleted_count == 0 {
return Err(ErrorKind::GridFs(GridFsErrorKind::FileNotFound {
identifier: GridFsFileIdentifier::Id(self.id),
})
.into());
}
Ok(())
}
}