how to authenticate mongoose connection mongodb in node.js

前端 未结 7 2089
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 04:38

I have created mongodb user with command

use admin
db.createUser(
    {
      user: \"superuser\",
      pwd: \"12345678\",
      roles: [ \"root\" ]
    }
)
         


        
7条回答
  •  南旧
    南旧 (楼主)
    2021-02-20 05:42

    I did run a mongo service using docker and then connected my mongoose to it with this code

    const _database = 'mongodb://user:pass@localhost:port/MyDB?authSource=admin';
    mongoose.connect(_database, {
        useNewUrlParser: true
    })
    .then(() => console.log('Connected to MongoDB ...'))
    .catch(err => console.error('Could not connect to MongoDB:‌', err));
    

    this is equal to

    mongo --username user --password pass --authenticationDatabase admin --port 27017
    

    on connection and then use MyDB database for doing operations like find, aggregate, insert and etc on it.

    if you have no user (MongoDB default user) for your database then you can change Database like bellow:

    const _database = 'mongodb://localhost:port/MyDB';
    

    27017 is default MongoDB port if your MongoDB port hasn't changed either then you can do the same for port too. like bellow:

    const _database = 'mongodb://localhost/MyDB';
    

    this is the same as bellow:

    mongo
    

    above code is because there is no user and no port then for not been a user there is no need for authentication database either.

提交回复
热议问题