如何在node.js中对猫鼬连接mongodb进行身份验证 [英] how to authenticate mongoose connection mongodb in node.js

查看:137
本文介绍了如何在node.js中对猫鼬连接mongodb进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用命令创建了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆