Connect to MongoDB
MongoDB is a NoSQL database that is used to store data in JSON-like format. To create a MongoDB database, follow the steps provided below.
Step 1: Go to MongoDB Atlas and Sign Up there.
Step 2: Once you signup, you will be forwarded to a page where your purpose to use MongoDB will be asked. Fill them as your wish.
Step 3: With step 2 being done, you will be routed to a page where configurational details will be asked. It will ask to select server, create an user, add your current IP, create an admin username and password. Filling these details, you will require to copy the string, that will be used to make a connection to the database. Here is a demonstration of how to do all of these.
Step 4: With that done, we can create a connection to the database created by importing mongoose and passing the connection string copied. We also ned to modify the username and password tag inside that string.
Node
const express = require(‘express’);
const cors = require(‘cors’);
const mongoose = require(‘mongoose’);
const app = express();
const PORT = 5000;
app.use(cors());
// MongoDB connection
mongoose.connect(‘mongodb+srv://<username>:<password>@mycluster.crwb89k.mongodb.net
/?retryWrites=true&w=majority&appName=mycluster’, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on(‘error’, console.error.bind(console, ‘MongoDB connection error:’));
db.once(‘open’, () => {
console.log(‘Connected to MongoDB’);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Getting Started with MERN Stack
M (MongoDB) E (Express.js) R (React.js) N (Node.js) stack is a popular Javascript language-based stack for building full-stack applications, MongoDB, ExpressJs, and NodeJs being responsible for server building and React for client-side development. This article is going to be your guide if you want to get started with the MERN stack development.
Table of Content
- 1. Setting Up Node.Js Environment
- 2. Starting a Node.Js Project and Installing Dependencies
- 3. Create a basic server with Express.Js
- 4. Connect to MongoDB
- 5. Define a Schema
- 6. Defining a Route and Query in a Database
- 7. Create a React App
- 8. Create a Component to Make a Backend Request
- 9. Combining Everything to Make a MERN Application
Contact Us