简体   繁体   English

MongoDB - 如何从集合中异步获取最后插入的记录

[英]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'.错误 CS0266 无法将类型“MongoDB.Driver.IFindFluent<BankingAppLibrary.Models.UserModel, BankingAppLibrary.Models.UserModel>”隐式转换为“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存在显式转换(您是否缺少转换?) 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> .您需要在IFindFluent<UserModel, UserModel>的末尾添加.FirstOrDefaultAsync()以便使用Task<UserModel>返回值。

And since your method is an asynchronous method, don't forget to add await as well.由于您的方法是异步方法,因此也不要忘记添加await

Your code should be as below:您的代码应如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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