简体   繁体   中英

MongoDB - How to get last inserted record from a collection asynchronously

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

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM