Step 2: To connect to your database, download a
package called mongodb. To use the package in your code, go to
index.js, and add the following near the top:
let mongodb = require(`mongodb`)
Add the following below the app variable:
let db
connectToDatabase()
async function connectToDatabase() {
let uri = `mongodb+srv://student:mrcode123@mrcode.uopds.mongodb.net/`
let client = await new mongodb.MongoClient(uri).connect()
db = client.db(`your-database-name`)
}
On the second line in the function, the connect method could take
some time to connect to MongoDB Atlas. Because of that, it returns a
Promise, which is an object that represents the eventual completion
of an asynchronous operation. The keyword
await
is used
to wait for the method to complete. Because await was used, the
keyword
async
must be placed in front of the function.
On the last line, change your-database-name to the name of your
database. The
db
object can be used to access your
database.