如何在node.js中对猫鼬连接mongodb进行身份验证 [英] how to authenticate mongoose connection mongodb in node.js
问题描述
我已经使用命令创建了mongodb用户
I have created mongodb user with command
use admin
db.createUser(
{
user: "superuser",
pwd: "12345678",
roles: [ "root" ]
}
)
然后在我的应用中,我试图像这样连接猫鼬
then in my app I am trying to connect mongoose like this
var options = {
user: "superuser",
pass: "12345678"
};
var mongooseConnectionString = 'mongodb://localhost/twitter-mongo';
mongoose.connect(mongooseConnectionString,options);
mongoose.model('User', UserSchema);
var User = mongoose.model('User');
通过猫鼬插入数据时出现此错误
I am getting this error when inserting data through mongoose
MongoError: not authorized for insert on twitter-mongo.users
请告诉我我的代码有什么问题
please tell me what is wrong in my code
推荐答案
您必须在连接字符串中声明authSource参数,以便指定包含用户凭据的数据库的名称:
You must declare the authSource parameter in your connection string in order to specify the name of the database that contains your user's credentials:
var options = {
user: "superuser",
pass: "12345678",
useMongoClient: true
};
var mongooseConnectionString = 'mongodb://localhost/twitter-mongo?authSource=admin';
请注意,我还将"useMongoClient"设置为true.这使请使用MongoClient进行身份验证并使用身份验证凭据进行连接,并且 open()已被弃用错误消息.
Note that I've also set "useMongoClient" to true. This silences the Please authenticate using MongoClient.connect with auth credentials and open() is deprecated error messages.
这篇关于如何在node.js中对猫鼬连接mongodb进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!