Add Option to Use MongoDB Credentials (#2169) by Ferotiq

* Add Option to Use MongoDB Credentials

* updated example

Co-authored-by: Jack <bartnikjack@gmail.com>
This commit is contained in:
Ferotiq 2021-12-13 10:00:09 -06:00 committed by GitHub
parent 707ffd3419
commit 53cbd9372b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 3 deletions

View file

@ -83,6 +83,8 @@ Follow these steps if you want to work on anything involving the database/accoun
1. Inside the backend folder, copy `example.env` to `.env` in the same directory.
1. If necessary, uncomment the lines in the `.env` file to use credentials to login to MongoDB.
1. Optional - Install [MongoDB-compass](https://www.mongodb.com/try/download/compass?tck=docs_compass). This tool can be used to see and manipulate your data visually.
1. To connect, type `mongodb://localhost:27017` in the connection string box and press connect. The monkeytype database will be created and shown` after the server is started`.

View file

@ -1,2 +1,8 @@
DB_NAME=monkeytype
DB_URI=mongodb://localhost:27017
DB_NAME=monkeytype
# You can also use the format mongodb://username:password@host:port or
# uncomment the following lines if you want to define them separately
# DB_USERNAME=
# DB_PASSWORD=
# DB_AUTH_MECHANISM="SCRAM-SHA-256"
# DB_AUTH_SOURCE=admin

View file

@ -4,10 +4,27 @@ let mongoClient;
module.exports = {
async connectDB() {
return MongoClient.connect(process.env.DB_URI, {
let options = {
useNewUrlParser: true,
useUnifiedTopology: true,
})
};
if (process.env.DB_USERNAME && process.env.DB_PASSWORD) {
options.auth = {
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
};
}
if (process.env.DB_AUTH_MECHANISM) {
options.authMechanism = process.env.DB_AUTH_MECHANISM;
}
if (process.env.DB_AUTH_SOURCE) {
options.authSource = process.env.DB_AUTH_SOURCE;
}
return MongoClient.connect(process.env.DB_URI, options)
.then((client) => {
mongoClient = client;
})