Created
July 22, 2019 23:02
-
-
Save zenkbaries/895fb566304c69cb93a603920d2f1bc8 to your computer and use it in GitHub Desktop.
How to establish an connecting with mongoDB with Promise and .catch()
This file contains 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
// | |
// Use this template to establish connection to MongoDB with Promise to handle error | |
// See documentation at https://mongoosejs.com/docs/connections.html | |
// If initial connection fails, it will not attempt to reconnect. | |
// It will attempt to reconnect if there's error AFTER the initial successful connection. | |
mongoose.connect(process.env.DB_URI, {useNewUrlParser: true}) | |
.then(() => { | |
console.log("MongoDB database initial connection established successfully."); | |
}) | |
.catch((err) => { | |
console.log("ERROR! Could not connect to Database!"); | |
console.log(err); | |
}); | |
// | |
// Use this to watch error events | |
// See documentation at https://mongoosejs.com/docs/connections.html#error-handling | |
// i.e. mongoose.connection.on(EVENT_TYPE, ()=>{HANDLE_EVENTS_HERE}); | |
const connection = mongoose.connection; | |
connection.on('disconnected',()=> {console.log('lost connection!')}); | |
connection.on('reconnected',()=> {console.log('reconnected to db again!')}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment