Skip to content
Snippets Groups Projects
Commit cebb00cc authored by Felipe D'Abrantes's avatar Felipe D'Abrantes
Browse files

Add delete method to base repository

parent a4f11947
No related branches found
No related tags found
1 merge request!25Add a question management page
......@@ -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)
}
}
......@@ -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")
}
})
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment