1

I have this code based on a mongodb connection example, I am trying to insert an object. but getting and error on the insertone line

This is the error data: MongoDB.Driver.MongoAuthenticationException: 'Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1.' Inner MongoCommandException: Command saslContinue failed: bad auth Authentication failed..

I am new using mongodb and got no idea of what is the error reason. Any help

static void Main(string[] args)
        {
            MongoClient dbClient = new MongoClient("mongodb+srv://dbUser:[email protected]/test?retryWrites=true&w=majority");
            var database = dbClient.GetDatabase("test");

            var collection = database.GetCollection<anyClassTest>("entities");
            var r = new anyClassTest() { name="Original", edad = 36, id = 1};
            collection.InsertOne(r);
        }

        public class anyClassTest
        {
            public string name { get; set; }
            public int edad { get; set; }
            public int id { get; set; }
        }
0

1 Answer 1

1

For standalone, direct connections, create the client the following way,

    var servers = new List<MongoServerAddress>() { new MongoServerAddress("hostname", 27017) };
    var credential = MongoCredential.CreateCredential("admin", "user", "pass");
    var mongoClientSettings = new MongoClientSettings()
    {
        ConnectionMode = ConnectionMode.Direct,
        Credential = credential,
        Servers = servers.ToArray(), 
        ApplicationName = "NameOfApp",
    };

    MongoClient client = new MongoClient(mongoClientSettings);

Once you have the client (connected), then you can get the database / collections and do what you need.

var database = client.GetDatabase("dbname");
var collection = database.GetCollection<anyClassTest>("entities");
var r = new anyClassTest() { name="Original", edad = 36, id = 1};
collection.InsertOne(r);
3
  • 1
    I am trying to connect to Atlas MongoDb, I am using the connection string from the web site example. there is no issue connecting or getting the database. the error is raised on the insertone line specifically. Commented May 19, 2020 at 20:10
  • Your error is very specific to Authentication. If you are not authenticating correctly, you will not be able to perform actions (Search / Insert / Update / Delete)
    – Jawad
    Commented May 19, 2020 at 20:58
  • You are completely right, it was my mistake. I was confused because the getdabase and getcollection thrown no exceptions, so I was thinking there was no issue with authentication. but you are right, I guess those methods does not validate these things. Thanks Commented May 22, 2020 at 19:36

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.