diff --git a/backend-services/feed-service/app/repositories/Repository.scala b/backend-services/feed-service/app/repositories/Repository.scala index b6eacb9b1a39133a8faa6d5096c319015bc0c2f8..43ea68e225574f1ebe602f7edf77e8e6e437d43c 100644 --- a/backend-services/feed-service/app/repositories/Repository.scala +++ b/backend-services/feed-service/app/repositories/Repository.scala @@ -126,4 +126,13 @@ class Repository[T: ClassTag](databaseName: String, collectionName: String) { def updateOne(documentId: ObjectId, updates: Seq[Bson]): Future[Unit] = { MongoConnection.updateOne[T](collection, documentId, updates) } + + /** + * Delete one document from the collection that matches the given ID. + * + * @param documentId The ID of the document to delete. + */ + def deleteOne(documentId: ObjectId): Future[Unit] = { + MongoConnection.deleteOne(collection, documentId) + } } diff --git a/backend-services/feed-service/app/utils/MongoConnection.scala b/backend-services/feed-service/app/utils/MongoConnection.scala index 6355414a44c28bcfccbcfc26ca97911173d9072b..da1ac5b8d612c8cfaabdd0ac7aa17015d943cc4a 100644 --- a/backend-services/feed-service/app/utils/MongoConnection.scala +++ b/backend-services/feed-service/app/utils/MongoConnection.scala @@ -2,7 +2,7 @@ package utils import org.mongodb.scala.{MongoClient, MongoDatabase, MongoCollection} import org.mongodb.scala.model.{Filters} -import com.mongodb.client.result.{InsertOneResult, UpdateResult} +import com.mongodb.client.result.{InsertOneResult, UpdateResult, DeleteResult} import org.bson.conversions.Bson import org.bson.types.ObjectId @@ -118,4 +118,26 @@ object MongoConnection { } }) } + + /** + * Delete one document from the collection that matches the given ID. + * + * @param collection The MongoCollection instance the document is in. + * @param documentId The ID of the document to delete. + * @throws RuntimeException if the delete was not acknowledged by the database. + */ + def deleteOne[T](collection: MongoCollection[T], documentId: ObjectId): Future[Unit] = { + val filter: Bson = Filters.equal[ObjectId]("_id", documentId) + val futureResult: Future[DeleteResult] = collection.deleteOne(filter).toFuture() + + futureResult.map[Unit]((result: DeleteResult) => { + if (!result.wasAcknowledged()) { + throw new RuntimeException("Delete was not acknowledged") + } + + if (result.getDeletedCount() == 0) { + throw new RuntimeException("Delete was not acknowledged") + } + }) + } }