# Mongoose connect using async/await

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jan 16, 2021, updated Oct 3, 2022. Topics: Node.js, Mongoose, MongoDB.
Canonical URL: https://attacomsian.com/blog/mongoose-connect-async-await

> A quick guide to learn how to use async-await to connect with MongoDB using Mongoose.

The `connect()` method provided by the [Mongoose](https://attacomsian.com/blog/nodejs-getting-started-with-mongoose) supports both JavaScript [promises](https://attacomsian.com/blog/promises-javascript) and [async-await](https://attacomsian.com/blog/async-await-javascript) syntax.

The following example demonstrates how you can use promises to create a connection with MongoDB:

```javascript
const mongoose = require('mongoose')

const server = '127.0.0.1:27017' // REPLACE WITH YOUR OWN SERVER
const database = 'test'          // REPLACE WITH YOUR OWN DB NAME

mongoose
  .connect(`mongodb://${server}/${database}`)
  .then(() => {
    console.log('MongoDB connected!!')
  })
  .catch(err => {
    console.log('Failed to connect to MongoDB', err)
  })
```

To use async-await syntax, you need to write an asynchronous function, as shown below:

```javascript
const mongoose = require('mongoose')

const server = '127.0.0.1:27017' // REPLACE WITH YOUR OWN SERVER
const database = 'test'          // REPLACE WITH YOUR OWN DB NAME

const connectDB = async () => {
  try {
    await mongoose.connect(`mongodb://${server}/${database}`)

    console.log('MongoDB connected!!')
  } catch (err) {
    console.log('Failed to connect to MongoDB', err)
  }
}

connectDB()
```

Read [this article](https://attacomsian.com/blog/nodejs-mongodb-local-connection) to learn more about setting up a MongoDB connection in Node.js.
