System.Nullreferenceexception: 'Undefined object reference for an instance of an object. ' Mongo was null

Asked

Viewed 7 times

0

I need to make a confirmation in the code, where the client inserts the cnpj and if it is already in the database, it will be possible to continue the registration, otherwise the code will be stopped. For this, I’m trying to take the field of mongodb and I’m using the Bsondocument, and it always returns me with the value null.

public class Mongo
    {
        public string cnpj { get; set; }
       
        public BsonDocument Conexao()
        {
           
            MongoClient dbClient = new MongoClient(urlbanco);

            var database = dbClient.GetDatabase(bancodedados);

            var collection = database.GetCollection<BsonDocument>("clientes");

            var filter = Builders<BsonDocument>.Filter.Eq("cnpj", cnpj);

            var document = collection.Find(filter).FirstOrDefault();


            return document;

        }

        public string MostrarDados()
        {
            BsonDocument mongo = Conexao();
            var cnpj = mongo["cnpj"].ToBson();
            List<String> listacnpj = mongo["cnpj"].AsBsonArray.Select(p => p.AsString).ToList();

            string teste = listacnpj[0].ToString();

            return teste;
        }
    }

Down here I’m using a windows form form to show:

 Console.WriteLine(mongo.MostrarDados());

where did I go wrong? I’m new and lost

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.