Skip to content

Commit

Permalink
Feat(find): add anyAsync()
Browse files Browse the repository at this point in the history
- to apply issue #3
  • Loading branch information
cpa-coder committed Nov 6, 2022
1 parent eb7dda4 commit df82ce7
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/MongoSharpen/Builders/Find.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,15 @@ public Task<List<T>> ManyAsync(Expression<Func<T, bool>> expression, Cancellatio
_filters = Builders<T>.Filter.Empty.Match(expression);
return ExecuteAsync(cancellation);
}

public async Task<bool> AnyAsync(CancellationToken cancellation = default)
{
Limit(1); //to prevent fetching more documents than needed

using var cursor = await ExecuteCursorAsync(cancellation).ConfigureAwait(false);
await cursor.MoveNextAsync(cancellation).ConfigureAwait(false);
return cursor.Current.Any();
}
}

public sealed class Find<T, TProjection> where T : IEntity
Expand Down
20 changes: 20 additions & 0 deletions tests/MongoSharpen.Test/DbContexts/DbContextTests.Find.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,26 @@ public async Task
result.Count.Should().Be(1);
}

[Fact]
public async Task find__on_execute_any__when_found__should_return_true()
{
var first = _bookFixture.Books.First();

var ctx = DbFactory.Get("library");
var result = await ctx.Find<Book>(x => x.MatchId(first.Id)).AnyAsync();

result.Should().BeTrue();
}

[Fact]
public async Task find__on_execute_any__when_not_found__should_return_false()
{
var ctx = DbFactory.Get("library");
var result = await ctx.Find<Book>(x => x.MatchId(Guid.NewGuid().ToString())).AnyAsync();

result.Should().BeFalse();
}

[Fact]
public async Task find__with_projection__when_no_filters__should_get_all()
{
Expand Down

0 comments on commit df82ce7

Please sign in to comment.