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.
1mongodb+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
1mongodb+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
123456789101112131415161718192021222324252627282930313233343536373839404142// 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!