oolongloop
oolongloop

Reputation: 135

Where do I connect my mongodb Atlas to my react app?

I am building a React app with node.js with mongodb Atlas database. I have created the mongodb Atlas cluster and need to connect it to the React app. The mongodb documentation says to use this code

var MongoClient = require('mongodb').MongoClient;

var uri = "mongodb+srv://kay:[email protected]/test";
MongoClient.connect(uri, function(err, client) {
   const collection = client.db("test").collection("devices");
   // perform actions on the collection object
   client.close();
});

But - I'm not exactly sure where in my React app it should go. I am using react-router-dom and most places I put it breaks the app. Any ideas?

Upvotes: 1

Views: 4002

Answers (1)

Roman Batsenko
Roman Batsenko

Reputation: 81

This code is designed to be used on server side of your app. As You've mentioned You have Node.js server, so put it there and use database connection to serve your data to the React client app. For example, You can send some data to client when your server receives HTTP request with some endpoint. Here is nice tutorial for that :)

Upvotes: 1

Related Questions