From 8f2629ff69fd61a474d4daf9c2a1948503883a3c Mon Sep 17 00:00:00 2001 From: Felipe D'Abrantes <felidabrantes@gmail> Date: Tue, 28 Mar 2023 22:21:05 +0100 Subject: [PATCH] Add mongo function to update a document --- .../app/models/MongoDBClient.scala | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/backend-services/feed-service/app/models/MongoDBClient.scala b/backend-services/feed-service/app/models/MongoDBClient.scala index 96c5dd63..ed6339e9 100644 --- a/backend-services/feed-service/app/models/MongoDBClient.scala +++ b/backend-services/feed-service/app/models/MongoDBClient.scala @@ -5,6 +5,7 @@ import utils.ConfigHelper import org.mongodb.scala.{MongoClient, MongoDatabase, MongoCollection, Document, FindObservable, Observer, Observable} import org.mongodb.scala.model.{Filters, Projections, Sorts} import org.bson.conversions.Bson +import org.bson.types.ObjectId import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future @@ -93,4 +94,23 @@ class MongoDBClient { } }) } + + /** + * Updates a document in a MongoDB collection. + * + * @param collection The MongoCollection instance the document is in. + * @param documentId The ID of the document to update. + * @param updates A sequence of Bson documents defining the updates. + * @throws RuntimeException if the update was not acknowledged by the database. + */ + def updateOne(collection: MongoCollection[Document], documentId: ObjectId, updates: Seq[Bson]): Future[Unit] = { + val filter = Filters.equal("_id", documentId) + val futureResult = collection.updateOne(filter, updates).toFuture() + + futureResult.map(result => { + if (!result.wasAcknowledged()) { + throw new RuntimeException("Update was not acknowledged") + } + }) + } } -- GitLab