Home > Software design >  Cannot await a .find method using mongodb c#
Cannot await a .find method using mongodb c#

Time:07-13

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

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.

CodePudding user response:

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;
    
        }
  • Related