我正在尝试使用mongoengine.connect()对MongoDB数据库进行身份验证。当我使用pymongo.MongoClient()时,代码可以正常工作,但是mongoenine.connect()会引发此错误:
pymongo.errors.OperationFailure: command createRole requires authentication
我相信连接参数是相同的,而且MongoEngine无论如何都使用PyMongo进行连接,所以我对这里的错误感到困惑。
我打印了PyMongo和MongoEngine返回的MongoClients,它们略有不同:
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())
read_preference是否会影响我的连接能力?
以下是进行调用的代码:
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)
如何使MongoEngine工作?我在这里做什么错了?
------更新5/9/19:
我尝试了以下代码:
user_admin_client = mongoengine.connect(
f'mongodb://{usern}:{pswd}@x.x.x.x/my_db'
)
print(user_admin_client)
我得到了以下内容:
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
我对为什么MongoClient现在尝试连接到本地主机感到有些困惑,因为我的IP地址肯定输入正确。甚至使用x.x.x.x:port
也无济于事。
答案 0 :(得分:1)
您需要在连接上使用void main() {
Injector injector = Injector();
injector.add(() => Person('Filip'));
injector.add(() => City('New York'));
Person person = injector.get<Person>();
City city = injector.get<City>();
print(person.name);
print(city.name);
}
class Person {
String name;
Person(this.name);
}
class City {
String name;
City(this.name);
}
typedef T CreateInstanceFn<T>();
class Injector {
static final Injector _singleton = Injector._internal();
final _factories = Map<String, dynamic>();
factory Injector() {
return _singleton;
}
Injector._internal();
String _generateKey<T>(T type) {
return '${type.toString()}_instance';
}
void add<T>(CreateInstanceFn<T> createInstance) {
final typeKey = _generateKey(T);
_factories[typeKey] = createInstance();
}
T get<T>() {
final typeKey = _generateKey(T);
T instance = _factories[typeKey];
if (instance == null) {
print('Cannot find instance for type $typeKey');
}
return instance;
}
}
参数
host
答案 1 :(得分:0)
我认为您在这里没有做错任何事情。
您能否尝试使用Mongo URI
本身通过MongoEngine连接。
类似的东西:
user_admin_client = mongoengine.connect('mongodb://{usern}:{pswd}@x.x.x.x/my_db')
print(user_admin_client)