how to authenticate mongoose connection mongodb in node.js

前端 未结 7 1965
没有蜡笔的小新
没有蜡笔的小新 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:24

    This is working fine:

    var options = { server: { socketOptions: { keepAlive: 1 } } };
    var connectionString = 'mongodb://admin:admin1234@localhost:27017/myDB';
    
     mongoose.connect(connectionString, options);
    
    //Add those events to get more info about mongoose connection:
    
    // Connected handler
    mongoose.connection.on('connected', function (err) {
      console.log("Connected to DB using chain: " + connectionString);
    });
    
    // Error handler
    mongoose.connection.on('error', function (err) {
      console.log(err);
    });
    
    // Reconnect when closed
    mongoose.connection.on('disconnected', function () {
       self.connectToDatabase();
    });
    

提交回复
热议问题