1. Overview of MERN Stack:
- MongoDB: NoSQL database for storing data in JSON-like documents.
- Express.js: Web application framework for Node.js to build APIs.
- React.js: Front-end library for building user interfaces.
- Node.js: JavaScript runtime for executing server-side code.
2. MongoDB:
- Basic Commands:
db.collection.find(): Query documents.
db.collection.insertOne(): Insert a single document.
db.collection.updateOne(): Update a document.
db.collection.deleteOne(): Delete a document.
- Mongoose:
- Use Mongoose for schema definitions and validation.
- Example Schema:
const mongoose = require('mongoose'); const UserSchema = new mongoose.Schema({ name: String, email: String, password: String, });
3. Express.js:
- Basic Setup:
const express = require('express'); const app = express(); app.use(express.json());
- Routing:
- Create routes using
app.get()
,app.post()
, etc. - Use
express.Router()
for modular routing.
- Create routes using
- Middleware:
- Use middleware for error handling, authentication, and logging.
4. React.js:
- Component Structure:
- Use functional components and hooks (e.g.,
useState
,useEffect
). - Example Component:
import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return <button onClick={() => setCount(count + 1)}>{count}</button>; };
- Use functional components and hooks (e.g.,
- State Management:
- Use Context API or libraries like Redux for global state management.
- Routing:
- Use
react-router-dom
for navigation between components.
import { BrowserRouter as Router, Route } from 'react-router-dom';
- Use
5. Node.js:
- Basic Server Setup:
const http = require('http'); const server = http.createServer(app); server.listen(3000, () => { console.log('Server is running on port 3000'); });
- APIs:
- Build RESTful APIs and connect them to the front-end.
6. Full-Stack Integration:
- API Calls: Use Axios or Fetch API in React to make HTTP requests to the Express backend.
- CORS: Enable CORS in Express for cross-origin requests.
const cors = require('cors'); app.use(cors());
7. Authentication:
- JWT (JSON Web Tokens):
- Use JWT for user authentication.
- Example:
const jwt = require('jsonwebtoken'); const token = jwt.sign({ userId: user._id }, 'secretkey');
- Passport.js: Optional library for more complex authentication strategies.
This Elysium Spark Note provides a solid foundation for mastering the MERN stack. Focus on building projects to apply these concepts, and keep exploring advanced topics as you MERN stack progress!