Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot await a .find method using mongodb c#

I am a novice so I apologize but I keep getting this CS1061 error when trying to await a .find() method. How do I await this find()?

MongoClient client = new MongoClient(mongoDBSettings.Value.ConnectionURI);
        IMongoDatabase database = client.GetDatabase(mongoDBSettings.Value.DatabaseName);
        _userCollection = database.GetCollection<User>(mongoDBSettings.Value.CollectionName);
        _partyCollection = database.GetCollection<Party>(mongoDBSettings.Value.CollectionName);
    

public async Task<IEnumerable> GetNearbyParties(string postalCode)
{

        var nearbyParties = await _partyCollection.Find(x => x.Address.postalCode == postalCode);

        return (IEnumerable<Party>)nearbyParties;

    }

MongoClient client = new MongoClient(mongoDBSettings.Value.ConnectionURI);
IMongoDatabase database = client.GetDatabase(mongoDBSettings.Value.DatabaseName);
_userCollection = database.GetCollection(mongoDBSettings.Value.CollectionName);
_partyCollection = database.GetCollection(mongoDBSettings.Value.CollectionName);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public async Task<IEnumerable> GetNearbyParties(string postalCode)
{

        var nearbyParties = await _partyCollection.Find(x => x.Address.postalCode == postalCode);

        return (IEnumerable<Party>)nearbyParties;

    }

I had it originally set up like this running synchronously:
public async Task<IEnumerable> GetNearbyParties(string postalCode)
{

        var nearbyParties = _partyCollection.Find(x => x.Address.postalCode == postalCode);

        return (IEnumerable<Party>)nearbyParties;

      
      



        //return results;
    }

But I understand that since it’s an async method I should have an await when I try to search the database so that other things can run while that is fetched.

>Solution :

You need to call asynchronous API of Mongo not normal Find method:

public async Task<IEnumerable> GetNearbyParties(string postalCode) {
    
            var nearbyParties = await _partyCollection.FindAsync(x => x.Address.postalCode == postalCode);
    
            return (IEnumerable<Party>)nearbyParties;
    
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading