Authentication failure while trying to save to mongodb

Solution 1:

Where, i.e. in which database did you create the user? Typically users are created in database admin. When you connect to a MongoDB then you should always specify the authentication database and the database you like to use.

The defaults are a bit confusing and not really consistent, see this table to get an overview:

+----------------------------------------------------------------------------------------+
|Connection string                                           | Authentication | Current  |
|                                                            | database       | database |
+----------------------------------------------------------------------------------------+
|mongo -u <...> -p <...> --authenticationDatabase admin myDB |     admin      |   myDB   |
|mongo -u <...> -p <...> myDB                                |     myDB       |   myDB   |
|mongo -u <...> -p <...> --authenticationDatabase admin      |     admin      |   test   |
|mongo -u <...> -p <...> localhost:27017                     |     test       |   test   |
|mongo -u <...> -p <...> --host localhost:27017              |     admin      |   test   |
|mongo -u <...> -p <...>                                     |     admin      |   test   |
+----------------------------------------------------------------------------------------+

If you like to use Connection string in URI format, it would correspond to these ones:

mongodb://<username>:<password>@hostname/myDB?authSource=admin
mongodb://<username>:<password>@hostname/myDB
mongodb://<username>:<password>@hostname?authSource=admin
mongodb://<username>:<password>@hostname

I guess you created the user in admin database but as you don't specify authenticationDatabase while connecting, Mongo defaults it to mydatabase where it fails, because user does not exist in database mydatabase.