Connect to mongodb docker container with authentication using mongoose and Nodejs

Anuradh
1 min readMay 19, 2019

--

prerequisites

Let’s Begin.

1. Create a new Node js project. (hope you are familiar with this)

2. install mongoose npm package.

3. your database config file should be like this or create a database config object.

module.exports = {
url: 'mongodb://localhost:27017/your_database_name',
user: 'username',
pwd: 'password'
}

4. Then connect to the database using mongoose as below, put this in your entry point.

mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.url, {
useNewUrlParser: true,
user: dbConfig.user,
pass: dbConfig.pwd
}).then(() => {
console.log('successfully connected to the database');
}).catch(err => {
console.log('error connecting to the database');
process.exit();
});

If you don’t know how to create a mongo database with authentication please visit how to create a mongdb database with authentication

Hope this will help to someone.

--

--