Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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))
@enheit
Copy link

enheit commented Mar 15, 2020

Thank you (:

@costa86
Copy link

costa86 commented Apr 9, 2020

That was very helpfull! Thanks a lot!

@afcajamarcar
Copy link

afcajamarcar commented May 13, 2020

Thank you very much kind sir.

@djibba22
Copy link

djibba22 commented Jul 30, 2020

awesome!

@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

lakshpandara commented May 17, 2022

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

CyberW0LF commented May 20, 2022

(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