Fix Retrieve updated document in ReplaceOneAsync method

This commit is contained in:
2025-08-07 17:23:44 -06:00
parent a97e4e2219
commit dbc21959eb
2 changed files with 22 additions and 9 deletions

View File

@@ -104,11 +104,13 @@ namespace Core.Blueprint.Mongo
void ReplaceOne(TDocument document); void ReplaceOne(TDocument document);
/// <summary> /// <summary>
/// Asynchronously replaces an existing document with a new one. /// Asynchronously replaces an existing document in the collection and returns the updated version.
/// </summary> /// </summary>
/// <param name="document">The document to replace the existing one.</param> /// <param name="document">The document with the updated data. Its _Id is used to locate the existing document.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> /// <returns>
Task ReplaceOneAsync(TDocument document); /// The updated document if the replacement was successful; otherwise, <c>null</c> if no matching document was found.
/// </returns>
Task<TDocument?> ReplaceOneAsync(TDocument document);
/// <summary> /// <summary>
/// Deletes a single document by the provided filter expression. /// Deletes a single document by the provided filter expression.

View File

@@ -175,16 +175,27 @@ namespace Core.Blueprint.Mongo
} }
/// <summary> /// <summary>
/// Asynchronously replaces an existing document in the collection. /// Asynchronously replaces an existing document in the collection and returns the updated version.
/// </summary> /// </summary>
/// <param name="document">The document with the updated data.</param> /// <param name="document">The document with the updated data. Its _Id is used to locate the existing document.</param>
/// <returns>A task that represents the asynchronous operation.</returns> /// <returns>
public virtual async Task ReplaceOneAsync(TDocument document) /// The updated document if the replacement was successful; otherwise, <c>null</c> if no matching document was found.
/// </returns>
public virtual async Task<TDocument?> ReplaceOneAsync(TDocument document)
{ {
var filter = Builders<TDocument>.Filter.Eq(doc => doc._Id, document._Id); var filter = Builders<TDocument>.Filter.Eq(doc => doc._Id, document._Id);
await _collection.FindOneAndReplaceAsync(filter, document);
var options = new FindOneAndReplaceOptions<TDocument>
{
ReturnDocument = ReturnDocument.After // return the updated document
};
var result = await _collection.FindOneAndReplaceAsync(filter, document, options);
return result;
} }
/// <summary> /// <summary>
/// Deletes a single document from the collection based on the provided filter expression. /// Deletes a single document from the collection based on the provided filter expression.
/// </summary> /// </summary>