Home > front end >  MongoDB - How to get last inserted record from a collection asynchronously
MongoDB - How to get last inserted record from a collection asynchronously

Time:12-04

I found a way to do it synchronously but I am unable to do it asynchronously.

public async Task<UserModel> GetLastCreatedUser()
{
    return _users
        .Find(_ => true)
        .SortByDescending(u => u.DateCreated)
        .Limit(1);
}

The synchronous way gives me this error:

Error CS0266 Cannot implicitly convert type 'MongoDB.Driver.IFindFluent<BankingAppLibrary.Models.UserModel, BankingAppLibrary.Models.UserModel>' to 'BankingAppLibrary.Models.UserModel'. An explicit conversion exists (are you missing a cast?) BankingAppLibrary C:\Users\lucas\source\repos\BankingApp\BankingAppLibrary\DataAccess\MongoUserData.cs 36 Active

CodePudding user response:

You need to add .FirstOrDefaultAsync() at the end of IFindFluent<UserModel, UserModel> in order to return the value with Task<UserModel>.

And since your method is an asynchronous method, don't forget to add await as well.

Your code should be as below:

public async Task<UserModel> GetLastCreatedUser()
{
    return await _users
        .Find(_ => true)
        .SortByDescending(u => u.DateCreated)
        .Limit(1)
        .FirstOrDefaultAsync();
}
  • Related