MongoDB  >  Connect your Mongo Cluster Locally

Connect your Mongo Cluster Locally

Optional: Setting up MongoDB Compass

Create your project and create a cluster in that project. There will be a password for the owner user of the cluster, which will be used for the connection string.

1
mongodb+srv://<DB_USER>:<DB_PASSWORD>@<CLUSTER_NAME>.poeupmz.mongodb.net/

DB_USER and CLUSTER_NAME fill already be filled out when you copy

Add a new connection in MongoDB Compass and enter the connection string. Now you should be able to see your cluster on your machine.

Connecting MongoDB to Project

In your .env.local file, create a variable to store your connection string

1
mongodb+srv://<DB_USER>:<DB_PASSWORD>@<CLUSTER_NAME>.poeupmz.mongodb.net/<DEFAULT_DB>?retryWrites=true&w=majority

<default_db> - Choose a default db in case you forget to pick one in the code

Create a mongodb.js file in a /src/lib directory to connect to mongodb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// src/lib/mongodb.js const { MongoClient } = require("mongodb"); let _client; let _clientPromise; /** Lazily create (and cache) a MongoClient connection promise. */ async function getMongoClient() { const uri = process.env.MONGODB_URI; if (!uri) { throw new Error( "MONGODB_URI is not set." ); } if (!_clientPromise) { _client = new MongoClient(uri); _clientPromise = _client.connect(); } return _clientPromise; } /** Convenience: get a DB handle (defaults to 'my_app'). */ async function getDb(name = "my_app") { const client = await getMongoClient(); return client.db(name); } const clientPromiseThenable = { then(onFulfilled, onRejected) { return getMongoClient().then(onFulfilled, onRejected); }, catch(onRejected) { return getMongoClient().catch(onRejected); }, finally(onFinally) { return getMongoClient().finally(onFinally); }, }; module.exports = clientPromiseThenable; module.exports.getMongoClient = getMongoClient; module.exports.getDb = getDb;

🙌 Congrats, you've connected Mongo to your computer and project!