I'm trying to authenticate for a MongoDB database using mongoengine.connect(). When I use pymongo.MongoClient() the code works perfectly, however mongoenine.connect() is throwing this error:
pymongo.errors.OperationFailure: command createRole requires authentication
I believe the connection parameters are identical and MongoEngine uses PyMongo to connect anyways, so I am confused about what is wrong here.
I printed the MongoClients returned by PyMongo and MongoEngine and they were slightly different:
Pymongo MongoClient:
MongoClient(host=['x.x.x.x:27017'], document_class=dict, tz_aware=False, connect=True)
MongoEngine MongoClient:
MongoClient(host=['x.x.x.x:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary())
Is the read_preference affecting my ability to connect somehow?
Here is the code making the calls:
user_admin_client = pymongo.MongoClient(
f'mongodb://{usern}:{pswd}@x.x.x.x/my_db'
)
print(user_admin_client)
user_admin_client = mongoengine.connect(db='my_db',
username=usern,
password=pswd,
host='x.x.x.x',
alias='init'
)
print(user_admin_client)
How can I get MongoEngine to work? What am I doing wrong here?
------ Update 5/9/19:
I tried the following code:
user_admin_client = mongoengine.connect(
f'mongodb://{usern}:{pswd}@x.x.x.x/my_db'
)
print(user_admin_client)
I got the following:
MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary())
...traceback...
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it
I'm a little confused as to why the MongoClient is now trying to connect to localhost, because my IP address is definitely correctly typed. Even using xxxx:port
did not do anything.
您需要在连接上使用host
参数
user_admin_client = mongoengine.connect(host='mongodb://{usern}:{pswd}@x.x.x.x/my_db')
I don't think you are doing anything wrong here.
Can you try using Mongo URI
itself to connect through MongoEngine.
Something like:
user_admin_client = mongoengine.connect('mongodb://{usern}:{pswd}@x.x.x.x/my_db')
print(user_admin_client)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.