Skip to content

Instantly share code, notes, and snippets.

@emilioriosvz
Created April 4, 2018 09:40
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save emilioriosvz/abdbe137737b830b21d66dc5f1236311 to your computer and use it in GitHub Desktop.
Save emilioriosvz/abdbe137737b830b21d66dc5f1236311 to your computer and use it in GitHub Desktop.
connect with mongoose using async/await
const mongoose = require('mongoose')
mongoose.Promise = Promise
mongoose.connection.on('connected', () => {
console.log('Connection Established')
})
mongoose.connection.on('reconnected', () => {
console.log('Connection Reestablished')
})
mongoose.connection.on('disconnected', () => {
console.log('Connection Disconnected')
})
mongoose.connection.on('close', () => {
console.log('Connection Closed')
})
mongoose.connection.on('error', (error) => {
console.log('ERROR: ' + error)
})
const run = async () => {
await mongoose.connect('mongodb://localhost:27017/emilioriosvz', {
autoReconnect: true,
reconnectTries: 1000000,
reconnectInterval: 3000
})
}
run().catch(error => console.error(error))
@TimLopesWork
Copy link

TimLopesWork commented Mar 11, 2021

Just to shorten it up a bit:
`
mongoose.Promise = Promise
mongoose.connection.on(
'connected', () => {
console.log('Connection Established')
},
'reconnected', () => {
console.log('Connection Reestablished')
},
'disconnected', () => {
console.log('Connection Disconnected')
},
'close', () => {
console.log('Connection Closed')
},
'error', (error) => {
console.log('ERROR: ' + error)
}

)

`

@lakshpandara
Copy link

const connectDB = async () => {
try {
const dbConnection = await mongoose.connect('mongodb://localhost:27017/react-ecommerce');

console.log(`MongoDB Connected: ${dbConnection.connection.host}`.cyan.underline);

} catch (error) {
console.error(Error: ${error.message}.red.underline.bold);
process.exit(1);
}
}

@CyberW0LF
Copy link

(async () => await mongoose.connect(DB_URL))().catch(console.log);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment