Tag Archives: TypeError: ‘Collection’ object is not callable. If you meant to call the ‘authenticate’ method on a ‘Database’ object it is failing because no such method exists.

[Solved] TypeError: ‘Collection’ object is not callable. If you meant to call the ‘authenticate’ method on a ‘Database’ object it is failing because no such method exists.

After installing the environment on the new computer these two days, it was found that the previous code could not authenticate the mongodb database user, and an error was reported, as shown in the title. After checking, it was found that there was a problem with the pymongo version

In pymongo version 3.9, the user authentication code is as follows:

self.client = pymongo.MongoClient(host="127.0.0.1", port=27017)
self.client["admin"].authenticate("admin", "12345678")

In pymongo 3.9 and before, it can run normally and perform user authentication. When I upgrade to 4.0, the error is reported as follows

Traceback (most recent call last):
  File "/Users/zzq/PycharmProjects/downloads_data/mongo_utils.py", line 34, in <module>
    mongo = Mongo()
  File "/Users/zzq/PycharmProjects/downloads_data/mongo_utils.py", line 13, in __init__
    print(self.client["admin"].authenticate("admin", "12345678"))
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pymongo/collection.py", line 2579, in __call__
    raise TypeError("'Collection' object is not callable. If you "
TypeError: 'Collection' object is not callable. If you meant to call the 'authenticate' method on a 'Database' object it is failing because no such method exists.

After viewing the official documents, it is found that the explanation is as follows:

4.0 document address: https://pymongo.readthedocs.io/en/stable/migrate-to-pymongo4.html#database-authenticate-and-database-logout-are-removed

It’s very clear here. In the new version, the previous authentication method is removed and the user name and password parameters are entered during instantiation, so my code is updated as follows:

self.client = pymongo.MongoClient(host="127.0.0.1", port=27017,username="admin",password="12345678")  # 地址  端口  用户名  密码

If you don’t know what version your pymongo is, you can use PIP3 list – V or pip list – V to view it and choose according to your situation

In addition to rewriting the code, you can also downgrade pymongo to 3.9   You can also make the code run normally. First, use PIP3 uninstall pymongo, enter y to delete it, and then specify the pymongo version as 3.9 when installing again: PIP3 install pymongo = = 3.9