Photo by benjamin lehman on Unsplash
Integrating MongoDB and React: A Perfect Match
TLDR; Using MongoClient, You can directly query MongoDB collections without APIs.
React is a powerful front-end framework for building user interfaces. However, it is solely focused on the view layer and does not have any opinions on how data is stored or retrieved. This flexibility allows developers to use any backend data source with React apps.
One popular choice for the backend is MongoDB, a document-oriented database. MongoDB stores data in JSON-like documents, which integrates nicely with JavaScript apps like React. In this post, I'll show you how to connect MongoDB directly from a React app using the MongoDB Node.js driver.
Why MongoDB and React?
MongoDB and React are a great stack for web applications for a few reasons:
JSON Documents - MongoDB stores data in documents, which are JSON-like objects. This format maps perfectly to JavaScript objects and integrates well with React's state and props.
Flexibility - Neither technology locks you into a strict schema or data model. MongoDB's schema-less documents give you the flexibility to evolve your data model over time. React also does not impose strict rules on how you structure your UI or state.
Popularity - MongoDB and React are very popular in the JavaScript ecosystem, and using them together is a stack that will be familiar to many web developers.
Javascript Drivers - MongoDB has first-class drivers for Node.js, the runtime environment for React apps. This makes integrating the database very straightforward in React projects.
Project Setup
To demonstrate connecting MongoDB and React, I'll start with a simple React app and show how to connect it to MongoDB.
First, install React and the Create-React-App tool and then create a React project called "react-mongo":
npm install -g create-react-app && create-react-app react-mongo
This will generate a React project with all the build setup configured. Next, install the MongoDB Node.js Driver:
npm install mongodb --save
Connecting to MongoDB
With the driver installed, open src/App.js in your React project. Add the following code to the top of the file to connect to MongoDB:
import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'reactmongo';
// Create a new MongoClient
const client = new MongoClient(url);
let db;
// Use connect method to connect to the server
client.connect(function(err) {
console.log('Connected successfully to server');
// Get the database
db = client.db(dbName);
});
This code creates a MongoClient and connects to our MongoDB server running locally on port 27017. It then gets a reference to the database named "reactmongo". We can access the db variable to query data.
Querying MongoDB from React
With the database connection, we can now query for data from our React components. For example, add this to your App.js:
export default function App(){
const [todos, setTodos] = React.useState([])
// text will be used later
const [text, setText] = React.useState('')
React.useEffect(() => {
// Get all todos
db.collection("todos").find({}).toArray(function(err, result) {
if (err) throw err;
setTodos(result);
});
},[])
return (
<div>
{todos.map(todo => (
<div>{todo.text}</div>
))}
</div>
);
}
This component will:
Query the "todos" collection in MongoDB when the component mounts
Store the results in the state
Render the todo texts
So you'll end up with a list of todos rendered from your MongoDB! You now have the basics of connecting MongoDB to your React app and querying for data.
Inserting Documents
Not only can we read from MongoDB, but we can insert new documents as well. For example, add this method to App.js:
addTodo(text) {
db.collection("todos").insertOne({ text }, (err, result) => {
if (err) throw err;
console.log('Document inserted');
});
}
Then call it from your render method:
<div>
<input onChange={e => setText(e.target.value)} />
<button onClick={() => addTodo(text)}>Add Todo</button>
</div>
This will allow adding new todos to the database from the React form.
Scaling for Production
When building for production, there are a few things to keep in mind:
Use MongoDB Atlas instead of a local database. Atlas is MongoDB's Database-as-a-Service and will handle scaling, backups, and security.
Wrap all database access in async/await instead of callbacks:
async function getTodos() { let client; try { client = await MongoClient.connect(url); db = client.db(dbName); todos = await db.collection("todos").find({}).toArray(); } catch (err) { console.log(err); } finally { client.close(); } setTodos(todos); }
Use environment variables to store the database URL instead of a hardcoded string.
Consider a backend API instead of accessing MongoDB directly from React. The backend can handle logic like database access control and scaling before serving data to React.
Now, this was the wrap for today's blog. As I've been writing blogs on both business and code, I'll be strictly following the routine of business and code separately. This week, it's all about js and its frameworks. Also, frameworks and other dev tools integrations. Happy Hacking! ❤️