Created
March 21, 2021 12:21
-
-
Save ChaseH88/6a4589c554ab943247f4c7247c8258bb to your computer and use it in GitHub Desktop.
MongoDB / Mongoose Class - A class that is setup and ready to go that allows you to connect to a particular MongoDB database instance.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import mongoose from 'mongoose'; | |
| interface DatabaseInterface { | |
| start(): void | |
| } | |
| class Database implements DatabaseInterface { | |
| private connection: string = ''; | |
| private username: string = 'YOUR_USERNAME'; | |
| private password: string = 'YOUR_PASSWORD'; | |
| private collection: string = 'YOUR_COLLECTION_NAME'; | |
| constructor(username?: string, password?: string, collection?: string){ | |
| // Update variables if provided | |
| if(Array.prototype.slice.call(arguments).length){ | |
| this.username = username!; | |
| this.password = password!; | |
| this.collection = collection!; | |
| } | |
| // Set the connection string | |
| this.connectionString(); | |
| } | |
| // Format the connection string with the local variables | |
| private connectionString = (): void => { | |
| this.connection = `mongodb+srv://${this.username}:${this.password}@chaseharrison.h2q0q.mongodb.net/${this.collection}?retryWrites=true&w=majority` | |
| }; | |
| // Initializes the connection with the database | |
| public start = async (): Promise<void> => { | |
| try { | |
| await mongoose.connect(this.connection, { | |
| useNewUrlParser: true, | |
| useUnifiedTopology: true | |
| }); | |
| return console.log('Database connection successful!'); | |
| } | |
| catch(err){ | |
| return console.error(`ERROR: ${err}`) | |
| } | |
| } | |
| } | |
| export { Database }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment