The MongoDB server is hosted in a docker container. Created a super user with root permission to login using username and password. Using pymodm to connect to MongoDB server from Python script.
I'm able to connect to the docker hosted MongoDB server from the shell as well as the Compass tool. The effort to connect and insert new items programatically using Python script fails with Authentication Failed error.
The script is as follows:
from pymodm import connect
from pymodm import MongoModel, fields
import urllib.parse
class Dummy(MongoModel):
email = fields.EmailField(primary_key=True)
name = fields.CharField()
class Meta:
connection_alias = 'Mongo'
# Establish a connection to the database.
mongo_uri = "mongodb://monadmin:" + urllib.parse.quote("myPassword@123") + "@192.168.x.x:27017/Test"
# Establish a connection to the database.
def Connect2DB()
try:
#connect('mongodb://localhost:27017/PMOTest')
connect(mongo_uri, alias="Mongo")
print("db connection success")
return True
except:
print("db connection failed")
return False
def Insert_record():
try:
Dummy(email="hello@test.com", name="test").save()
print("save success")
except ex:
print("save failed")
if __name__ == "__main__":
if Connect2DB():
Insert_record()
The connection succeeds but the insert record is failing with the following error: pymongo.errors.OperationFailure: Authentication failed
mongo_uri = "mongodb://monadmin:" + urllib.parse.quote("myPassword@123") + "@192.168.x.x:27017/Test?authSource=admin
You need to add the ?authSource=admin
For the mongo docker image I am using, It contained a database called admin. To use the admin database for authentication you have to tell the command to authenticate against this by adding the authSource part to your uri.