NODE-201 Sprint Summary

Modified on Tue, 13 Aug at 6:17 PM

TABLE OF CONTENTS


NodeJS

What is NodeJS?

What is it?

Node.js is an open-source, cross-platform runtime environment that allows you to run JavaScript code outside of a browser. It uses Chrome's V8 JavaScript engine.


Where is it used?

Node.js is commonly used for server-side development, building web applications, APIs, and real-time applications such as chat applications.


How is it used?

Node.js enables developers to use JavaScript for writing server-side logic, making it possible to have a unified language stack for both client and server code.


Best Practices/Pitfalls to Avoid

Best Practices: Use asynchronous methods to handle I/O operations, structure your code using modules, and handle errors properly.

Pitfalls to Avoid: Avoid blocking the event loop with CPU-intensive tasks, and do not ignore error handling.


npm

What is it?

npm (Node Package Manager) is a package manager for JavaScript and Node.js.


Where is it used?

It is used to install, share, and manage dependencies in Node.js projects.


How is it used?

Developers use npm commands to install libraries, manage project dependencies, and run scripts.


sh
  // Initializing a new Node.js project
  npm init -y

  // Installing Express.js
  npm install express


Best Practices/Pitfalls to Avoid

Best Practices: Regularly update dependencies, use `package-lock.json` to ensure consistent installs, and understand the license of each package.

Pitfalls to Avoid: Avoid using outdated packages and do not install unnecessary dependencies.


package.json

What is it?

 package.json is a JSON file that contains metadata about the Node.js project and its dependencies.


Where is it used?

It is used in every Node.js project to manage project information, scripts, and dependencies.


How is it used?

It is automatically created when initializing a Node.js project and is used to keep track of dependencies and project scripts.


json
  {
    "name": "my-app",
    "version": "1.0.0",
    "description": "My first Node.js app",
    "main": "index.js",
    "scripts": {
      "start": "node index.js"
    },
    "dependencies": {
      "express": "^4.17.1"
    }
  }

Best Practices/Pitfalls to Avoid

Best Practices: Keep `package.json` updated with all dependencies, use meaningful version numbers, and utilize scripts for common tasks.

Pitfalls to Avoid: Avoid manually editing `node_modules` directory and do not ignore dependency vulnerabilities.


Modules

What is it?

Modules are individual pieces of reusable code that can be imported and exported in Node.js.


Where is it used?

Modules are used to organize and encapsulate functionality in Node.js applications.


How is it used?

Node.js uses `require` to import modules and `module.exports` to export them.


javascript
  // math.js - Module
  module.exports.add = (a, b) => a + b;

  // app.js - Importing and using the module
  const math = require('./math');
  console.log(math.add(2, 3)); // Outputs: 5

Best Practices/Pitfalls to Avoid:

Best Practices: Use modular design to keep code manageable, name modules clearly, and keep each module focused on a single responsibility.

Pitfalls to Avoid: Avoid circular dependencies and do not expose sensitive data through modules.


Creating an HTTP Server with NodeJS


What is it?

Creating an HTTP server in Node.js involves using the built-in `http` module to handle incoming HTTP requests and send responses.


Where is it used?

It is used in web applications to serve content and handle client-server communication.


How is it used?

By creating an instance of `http.Server` and defining request and response handlers.


javascript
  const http = require('http');

  const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World\n');
  });

  server.listen(3000, () => {
    console.log('Server running at http://127.0.0.1:3000/');
  });

Best Practices/Pitfalls to Avoid:

Best Practices: Use environment variables for configuration, handle different HTTP methods appropriately, and ensure security headers are set.

 Pitfalls to Avoid: Avoid hardcoding values and not handling different types of requests (e.g., GET, POST).


Request and Response Objects


What is it?

The `req` (request) and `res` (response) objects represent the incoming request and outgoing response in an HTTP transaction.

Where is it used?

These objects are used in HTTP server code to access request data and send responses.

How is it used?

By interacting with properties and methods of `req` and `res` within the request handler function.


javascript
  const http = require('http');

  const server = http.createServer((req, res) => {
    console.log(req.method, req.url); // Request object
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World\n'); // Response object
  });

  server.listen(3000, () => {
    console.log('Server running at http://127.0.0.1:3000/');
  });

Best Practices/Pitfalls to Avoid

Best Practices: Properly parse incoming request data, set appropriate response headers, and handle errors gracefully.

Pitfalls to Avoid: Avoid blocking the request handler with synchronous operations and ensure all responses end with `res.end()`.


ExpressJS


What is ExpressJS?


What is it?

Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.


Where is it used?

It is used to build web applications and APIs with ease.


How is it used?

By defining routes and middleware to handle HTTP requests and responses.


javascript
  const express = require('express');
  const app = express();

  app.get('/', (req, res) => {
    res.send('Hello World');
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid:

Best Practices: Use middleware for common tasks (e.g., parsing JSON), structure routes logically, and handle errors with middleware.

Pitfalls to Avoid: Avoid cluttering the main application file and ensure middleware is applied in the correct order.


HTTP Server with ExpressJS


What is it?

An HTTP server built with Express.js to handle HTTP requests and send responses.


Where is it used?

Used in web applications to manage routes and server logic.


How is it used?

By setting up route handlers and starting the server with `app.listen`.


javascript
  const express = require('express');
  const app = express();

  app.get('/', (req, res) => {
    res.send('Hello World');
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid:

Best Practices: Use environment variables for configuration, log all requests, and validate incoming data.

Pitfalls to Avoid: Avoid hardcoding port numbers and not handling different types of HTTP methods.


Path and Query Params in ExpressJS


What is it?

Path parameters are dynamic segments in the URL, and query parameters are key-value pairs in the URL query string.


Where is it used?

Used to capture and use dynamic data from the URL in route handlers.


How is it used?

By defining routes with parameters and accessing them via `req.params` and `req.query`.


javascript
  const express = require('express');
  const app = express();

  // Path params
  app.get('/users/:id', (req, res) => {
    res.send(`User ID: ${req.params.id}`);
  });

  // Query params
  app.get('/search', (req, res) => {
    res.send(`Search Query: ${req.query.q}`);
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid:

Best Practices: Validate and sanitize user input, provide meaningful error messages, and use descriptive route names.

Pitfalls to Avoid: Avoid exposing sensitive data through URL parameters and ensure parameter values are properly encoded.


Controllers


What is it?

Controllers are functions that handle the logic for processing requests and returning responses.


Where is it used?

Used to separate route definitions from business logic.


How is it used?

By defining controller functions and using them in route handlers.


javascript
  const express = require('express');
  const app = express();

  const userController = {
    getUser: (req, res) => {
      res.send('Get User');
    },
  };

  app.get('/user', userController.getUser);

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid 

Best Practices: Keep controllers focused on specific tasks, use services for business logic, and handle errors within controllers.

Pitfalls to Avoid: Avoid putting too much logic in controllers and ensure they are testable.


Routes


What is it?

Routes define the endpoints in an application to handle specific requests.


Where is it used?

Used to map URLs to specific handlers in web applications.


How is it used?

By defining route handlers and using them with the `app` object.


javascript
  const express = require('express');
  const router = express.Router();

  router.get('/home', (req, res) => {
    res.send('Home Page');
  });

  const app = express();
  app.use('/', router);

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid

Best Practices: Organize routes logically, use route parameters where necessary, and document routes.

Pitfalls to Avoid: Avoid duplicating route logic and ensure routes are secure.


Joi for Data Validation


What is it?

Joi is a library for schema description and data validation.


Where is it used?

Used to validate request data against predefined schemas in web applications.


How is it used?

By defining validation schemas and using them to validate incoming data.


javascript
  const express = require('express');
  const Joi = require('joi');

  const app = express();
  app.use(express.json());

  const schema = Joi.object({
    name: Joi.string().min(3).required()
  });

  app.post('/user', (req, res) => {
    const { error } = schema.validate(req.body);
    if (error) return res.status(400).send(error.details[0].message);
    res.send('User created');
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid

Best Practices: Validate all incoming data, use schemas to enforce data structure, and provide clear error messages.

Pitfalls to Avoid: Avoid skipping validation and ensure validation logic is not duplicated in multiple places.


dotenv


What is it?

dotenv is a zero-dependency module that loads environment variables from a `.env` file into `process.env`.


Where is it used?

Used to manage environment-specific configurations in Node.js applications.


How is it used?

By creating a `.env` file and loading its variables using `dotenv`.


javascript
  require('dotenv').config();

  const express = require('express');
  const app = express();
  const port = process.env.PORT || 3000;

  app.get('/', (req, res) => {
    res.send('Hello World');
  });

  app.listen(port, () => {
    console.log(`Server running on port ${port}`);
  });

Best Practices/Pitfalls to Avoid


Best Practices: Use `.env` files for environment-specific configurations, keep `.env` files out of version control, and validate environment variables.

 Pitfalls to Avoid: Avoid hardcoding configuration values and ensure sensitive information is not exposed.


Middleware - Globally and Selectively Applying Middleware


What is it?

Middleware functions are functions that have access to the request and response objects and can modify them.


Where is it used?

Used to add functionality to the request handling pipeline, such as logging, authentication, and validation.


How is it used?

By defining middleware functions and applying them globally or selectively.


javascript
  const express = require('express');
  const app = express();

  // Global middleware
  const logger = (req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();
  };

  app.use(logger);

  // Selective middleware
  app.get('/admin', logger, (req, res) => {
    res.send('Admin Page');
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid 

Best Practices:  Apply middleware only where needed, chain middleware functions effectively, and handle errors within middleware.

Pitfalls to Avoid:  Avoid overloading global middleware and ensure middleware is not blocking the event loop.


Validators


What is it? 

Functions or libraries used to validate data.


Where is it used? 

Used in web applications to ensure that data meets specific criteria before processing.


How is it used?

By defining validation schemas or functions and using them to validate incoming data.


javascript
  const express = require('express');
  const Joi = require('joi');

  const app = express();
  app.use(express.json());

  const schema = Joi.object({
    email: Joi.string().email().required(),
  });

  app.post('/user', (req, res) => {
    const { error } = schema.validate(req.body);
    if (error) return res.status(400).send(error.details[0].message);
    res.send('User created');
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid 

Best Practices:  Validate all incoming data, use descriptive error messages, and keep validation logic reusable.

Pitfalls to Avoid:  Avoid bypassing validation and ensure all fields are validated.


Service Layer


What is it? 

A layer in the application that handles business logic.


Where is it used? 

Used to separate business logic from controllers in web applications.


How is it used?

By defining service functions that encapsulate business logic and calling them from controllers.


javascript
  const express = require('express');
  const app = express();

  const userService = {
    createUser: (data) => {
      // Business logic for creating a user
      console.log('User created with data:', data);
    },
  };

  app.post('/user', (req, res) => {
    userService.createUser(req.body);
    res.send('User created');
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid 

Best Practices: Keep services focused on specific business logic, ensure services are reusable, and handle errors within the service layer.

Pitfalls to Avoid: Avoid duplicating business logic across controllers and ensure services are decoupled from the presentation layer.


Layered Architecture


What is it? 

An architectural pattern that separates an application into different layers, such as controllers, services, and models.


Where is it used? 

Used to organize code in a maintainable and scalable way in web applications.


How is it used?

By structuring the code into separate directories and files based on their roles.


  /controllers
  /services
  /models
  /routes

Best Practices/Pitfalls to Avoid 

Best Practices: Follow the Single Responsibility Principle, keep layers decoupled, and ensure each layer has a clear purpose.

Pitfalls to Avoid: Avoid tight coupling between layers and ensure that each layer can be tested independently.


Debugging Express Apps


What is it? 

The process of identifying and fixing issues in an Express.js application.


Where is it used? 

Used during development to troubleshoot and resolve errors in the application.


How is it used?

By using tools like the built-in `debug` module, logging, and breakpoints.


javascript
  const express = require('express');
  const debug = require('debug')('app');
  const app = express();

  app.get('/', (req, res) => {
    debug('Home route');
    res.send('Hello World');
  });

  app.listen(3000, () => {
    debug('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid 

Best Practices: Use meaningful log messages, leverage debugging tools, and handle errors properly.

Pitfalls to Avoid: Avoid leaving debug code in production and ensure logs do not expose sensitive information.


bcrypt, Hashed Passwords, and Verifying Hashed Passwords


What is it? 

bcrypt is a library for hashing passwords.


Where is it used? 

Used to securely store and verify user passwords in web applications.


How is it used?

By hashing passwords before storing them in the database and verifying them during login.


javascript
  const bcrypt = require('bcrypt');

  const hashPassword = async

 (password) => {
    const salt = await bcrypt.genSalt(10);
    const hashed = await bcrypt.hash(password, salt);
    return hashed;
  };

  const verifyPassword = async (password, hashed) => {
    return await bcrypt.compare(password, hashed);
  };

  app.post('/signup', async (req, res) => {
    const hashedPassword = await hashPassword(req.body.password);
    // Save user with hashed password
    res.send('User registered');
  });

  app.post('/login', async (req, res) => {
    const user = // fetch user from database
    const validPassword = await verifyPassword(req.body.password, user.password);
    if (!validPassword) return res.status(400).send('Invalid password');
    res.send('Logged in');
  });

Best Practices/Pitfalls to Avoid 

Best Practices: Use a strong salt and hash passwords, store only the hashed password, and use secure password policies.

Pitfalls to Avoid: Avoid storing plain text passwords and do not use weak hashing algorithms.


Sign-up and Login Routes


What is it? 

Routes for handling user registration and authentication.


Where is it used? 

Used in web applications to allow users to sign up and log in.


How is it used?

By defining routes and handling user data securely.


javascript
  const express = require('express');
  const app = express();
  app.use(express.json());

  app.post('/signup', async (req, res) => {
    const hashedPassword = await hashPassword(req.body.password);
    // Save user with hashed password
    res.send('User registered');
  });

  app.post('/login', async (req, res) => {
    const user = // fetch user from database
    const validPassword = await verifyPassword(req.body.password, user.password);
    if (!validPassword) return res.status(400).send('Invalid password');
    // Generate token and send response
    res.send('Logged in');
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid 

Best Practices: Validate user input, hash passwords before storing, and use secure tokens for authentication.

Pitfalls to Avoid: Avoid storing sensitive data insecurely and ensure authentication tokens are securely generated.


Login Flow


What is it? 

The process of authenticating a user during login.


Where is it used? 

Used in web applications to verify user credentials and start a session.


How is it used?

By validating user input, checking credentials, and setting up session tokens.


javascript
  const express = require('express');
  const app = express();
  app.use(express.json());

  app.post('/login', async (req, res) => {
    const user = // fetch user from database
    const validPassword = await verifyPassword(req.body.password, user.password);
    if (!validPassword) return res.status(400).send('Invalid password');
    // Generate token and send response
    res.send('Logged in');
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid 

Best Practices: Use secure tokens, validate input thoroughly, and ensure proper error messages.

Pitfalls to Avoid: Avoid exposing sensitive information in error messages and ensure tokens are securely stored.


JWT


What is it? 

JSON Web Tokens (JWT) are a compact, URL-safe means of representing claims to be transferred between two parties.


Where is it used? 

Used for secure transmission of information between parties as a JSON object.


How is it used?

By generating and verifying tokens during authentication and authorization.


javascript
  const jwt = require('jsonwebtoken');

  const generateToken = (user) => {
    return jwt.sign({ id: user.id }, 'secret', { expiresIn: '1h' });
  };

  const verifyToken = (token) => {
    try {
      return jwt.verify(token, 'secret');
    } catch (err) {
      return null;
    }
  };

  app.post('/login', (req, res) => {
    const user = // fetch user from database
    const token = generateToken(user);
    res.send({ token });
  });

  app.get('/protected', (req, res) => {
    const token = req.headers['authorization'];
    const payload = verifyToken(token);
    if (!payload) return res.status(401).send('Unauthorized');
    res.send('Protected resource');
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid 

Best Practices: Use secure keys for signing tokens, set appropriate expiration times, and validate tokens thoroughly.

Pitfalls to Avoid: Avoid storing tokens insecurely and ensure tokens are not easily guessable.


Setting Cookies


What is it? 

Cookies are small pieces of data sent from a server and stored on the client's device.


Where is it used? 

Used to store user-specific information on the client-side for session management and tracking.


How is it used?

By using the `res.cookie` method in Express.js to set cookies.


javascript
  const express = require('express');
  const cookieParser = require('cookie-parser');
  const app = express();
  app.use(cookieParser());

  app.get('/setcookie', (req, res) => {
    res.cookie('name', 'value', { httpOnly: true });
    res.send('Cookie set');
  });

  app.get('/getcookie', (req, res) => {
    const cookie = req.cookies['name'];
    res.send(`Cookie value: ${cookie}`);
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid 

Best Practices: Use secure and HTTP-only flags for cookies, set appropriate expiration times, and validate cookie values.

Pitfalls to Avoid: Avoid storing sensitive data in cookies and ensure cookies are not accessible via JavaScript.


CORS

What is it? Cross-Origin Resource Sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the resource originated.


Where is it used? Used to enable or restrict resources requested from a domain different from the domain serving the web application.


How is it used?

By setting appropriate headers or using the `cors` middleware in Express.js.


javascript
  const express = require('express');
  const cors = require('cors');
  const app = express();

  app.use(cors());

  app.get('/', (req, res) => {
    res.send('CORS enabled');
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid 

 Best Practices: Restrict CORS to specific domains, use appropriate methods and headers, and handle preflight requests.

Pitfalls to Avoid: Avoid enabling CORS for all domains in production and ensure CORS policies are properly configured.


Authorizing Requests using PassportJS


What is it? 

Passport.js is middleware for Node.js that simplifies the process of authenticating requests.


Where is it used? 

Used to authenticate and authorize users in web applications.


How is it used?

By configuring Passport strategies and applying them to routes.


javascript
  const express = require('express');
  const passport = require('passport');
  const LocalStrategy = require('passport-local').Strategy;
  const app = express();

  passport.use(new LocalStrategy(
    (username, password, done) => {
      // Fetch user and verify credentials
      const user = // fetch user from database
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!validPassword(password, user.password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    }
  ));

  app.post('/login', passport.authenticate('local', {
    successRedirect: '/dashboard',
    failureRedirect: '/login',
  }));

  app.get('/dashboard', (req, res) => {
    if (!req.isAuthenticated()) return res.status(401).send('Unauthorized');
    res.send('Welcome to your dashboard');
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Best Practices/Pitfalls to Avoid 

Best Practices: Use appropriate authentication strategies, handle errors gracefully, and ensure secure storage of user credentials.

Pitfalls to Avoid: Avoid exposing sensitive information during authentication and ensure that authentication mechanisms are up-to-date.


MongoDB


What is MongoDB?


What is it? 

MongoDB is a NoSQL, document-oriented database.


Where is it used? 

Used in applications that require flexible, scalable data storage.


How is it used?

By storing data in JSON-like documents with dynamic schemas.


Best Practices/Pitfalls to Avoid 

Best Practices: Design schemas to match application requirements, use indexes for performance, and ensure proper data validation.

Pitfalls to Avoid: Avoid unnecessary nesting of documents and ensure collections are properly indexed.


SQL vs NoSQL DB


What is it? 

SQL databases are relational, table-based databases, whereas NoSQL databases are non-relational and can be document-based, key-value pairs, wide-column stores, or graph databases.


Where is it used? SQL is used in applications requiring complex queries and ACID transactions. NoSQL is used for scalable, flexible schema storage.


How is it used?

SQL uses structured query language for defining and manipulating data. NoSQL uses varied means of querying and storing data.


Best Practices/Pitfalls to Avoid 

Best Practices: Choose the database type that best fits the application requirements, understand the strengths and weaknesses of each, and ensure data integrity.

Pitfalls to Avoid: Avoid using a database type that does not align with the application's needs and ensure that the data model is appropriately designed.


JSON and BSON


What is it? 

JSON (JavaScript Object Notation) is a lightweight data interchange format. BSON (Binary JSON) is a binary-encoded serialization of JSON-like documents.


Where is it used? 

JSON is used for data interchange between client and server. BSON is used internally in MongoDB for efficiency.


How is it used?

JSON is human-readable and used in APIs. BSON is optimized for speed and used in MongoDB storage.


Best Practices/Pitfalls to Avoid 

Best Practices: Use JSON for data interchange due to its readability, and utilize BSON for efficient storage in MongoDB.

Pitfalls to Avoid: Avoid converting large amounts of data between JSON and BSON unnecessarily and ensure the data format is suitable for the use case.


mongo shell


What is it? 

mongo shell is an interactive JavaScript interface to MongoDB.


Where is it used? Used for database operations such as querying, updating data, and administrative tasks.


How is it used?

By typing MongoDB commands directly into the shell.


sh
  // Starting mongo shell
  mongo

  // Finding all documents in a collection
  db.collection.find()

Best Practices/Pitfalls to Avoid 

Best Practices: Use the mongo shell for quick and direct database operations, and script common tasks for consistency.

Pitfalls to Avoid: Avoid running untested commands on production databases and ensure backup strategies are in place.


Database, Collections, and Documents in MongoDB


What is it? 

A database contains collections, and collections contain documents.


Where is it used? 

Used to organize and store data in MongoDB.


How is it used?

By creating databases, adding collections, and inserting documents.


javascript
  // Connecting to MongoDB and using a database
  const { MongoClient } = require('mongodb');
  const uri = 'mongodb://localhost:27017';
  const client = new MongoClient(uri);

  async function run() {
    try {
      await client.connect();
      const database = client.db('myDatabase');
      const collection = database.collection('myCollection');

      // Inserting a document
      const doc = { name: 'John', age: 30 };
      await collection.insertOne(doc);

      // Finding a document
      const result = await collection.findOne({ name: 'John' });
      console.log(result);
    } finally {
      await client.close();
    }
  }

  run().catch(console.dir);

Best Practices/Pitfalls to Avoid 

Best Practices: Use meaningful collection names, design schemas that fit the application’s requirements, and ensure efficient indexing.

Best Practices: Avoid using too many collections or nesting documents too deeply, which can lead to performance issues.


CRUD Operations Using mongo shell


What is it? 

CRUD stands for Create, Read, Update, and Delete operations.


Where is it used? 

Used to manipulate data in MongoDB collections.


How is it used? 
By executing CRUD operations in the mongo shell.


sh
  // Inserting a document
  db.collection.insertOne({ name: 'Alice', age: 25 });

  // Finding documents
  db.collection.find({ age: { $gt: 20 } });

  // Updating a document
  db.collection.updateOne({ name: 'Alice' }, { $set: { age: 26 } });

  // Deleting a document
  db.collection.deleteOne({ name: 'Alice' });

Best Practices/Pitfalls to Avoid 

Best Practices: Perform CRUD operations efficiently, use indexes for quick searches, and validate data before inserting.

Pitfalls to Avoid: Avoid unnecessary updates that modify many documents and ensure that deletions are performed carefully to avoid data loss.


Mongoose ODM


What is it? 

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js.


Where is it used? 

Used to manage relationships between data and provides schema validation.


How is it used?

By defining schemas and models in Mongoose and using them to interact with MongoDB.


javascript
  const mongoose = require('mongoose');

  mongoose.connect('mongodb://localhost:27017/myDatabase', { useNewUrlParser: true, useUnifiedTopology: true });

  const userSchema = new mongoose.Schema({
    name: String,
    age: Number
  });

  const User = mongoose.model('User', userSchema);

  // Creating a new user
  const user = new User({ name: 'Bob', age: 28 });
  user.save().then(() => console.log('User saved'));

Best Practices/Pitfalls to Avoid 

Best Practices: Define clear schemas, use Mongoose validation, and take advantage of Mongoose middleware.

Pitfalls to Avoid: Avoid overly complex schemas and ensure proper error handling with Mongoose.


Mongoose Connect


What is it? 

The method to establish a connection to a MongoDB database using Mongoose.


Where is it used? 

Used at the start of a Node.js application to connect to the database.


How is it used?

By calling `mongoose.connect` with the database URI and options.


javascript
  const mongoose = require('mongoose');

  mongoose.connect('mongodb://localhost:27017/myDatabase', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('MongoDB connected'))
    .catch(err => console.error('Connection error', err));

Best Practices/Pitfalls to Avoid 

Best Practices: Handle connection errors, use connection pooling, and close connections gracefully.

Pitfalls to Avoid: Avoid hardcoding connection strings and ensure secure connection settings.


Mongoose Schema, Nested Schema, and Model


What is it? 

Schema defines the structure of documents within a collection. Nested schema allows embedding documents within documents. Model provides an interface to the database for CRUD operations.


Where is it used? 

Used to define data structure and constraints in MongoDB.


How is it used?

By defining schemas and creating models from them.


javascript
  const mongoose = require('mongoose');

  const addressSchema = new mongoose.Schema({
    street: String,
    city: String
  });

  const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
    address: addressSchema
  });

  const User = mongoose.model('User', userSchema);

  const user = new User({ name: 'Charlie', age: 32, address: { street: '123 Main St', city: 'New York' } });
  user.save().then(() => console.log('User with nested address saved'));

Best Practices/Pitfalls to Avoid 

Best Practices: Keep schemas lean, use nested schemas wisely, and leverage Mongoose validation.

Pitfalls to Avoid: Avoid deeply nested schemas that can affect performance and ensure data integrity with schema validation.


CRUD Operations Using Mongoose


What is it? 

CRUD operations in Mongoose include create, read, update, and delete.


Where is it used? 

Used to manipulate data in MongoDB using Mongoose models.


How is it used?

By calling methods on Mongoose models.


javascript
  const mongoose = require('mongoose');

  const addressSchema = new mongoose.Schema({
    street: String,
    city: String
  });

  const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
    address: addressSchema
  });

  const User = mongoose.model('User', userSchema);

  const user = new User({ name: 'Charlie', age: 32, address: { street: '123 Main St', city: 'New York' } });
  user.save().then(() => console.log('User with nested address saved'));

Best Practices/Pitfalls to Avoid 

Best Practices: Use appropriate Mongoose methods for CRUD operations, handle errors, and validate data.

Pitfalls to Avoid: Avoid direct updates that bypass validation and ensure atomic operations where necessary.


Aggregates


What is it? 

Aggregation operations process data records and return computed results.


Where is it used? 

Used to perform complex data transformations and computations in MongoDB.


How is it used?

By using the `aggregate` method with pipeline stages.


javascript
  const mongoose = require('mongoose');

  const userSchema = new mongoose.Schema({
    name: String,
    age: Number
  });

  const User = mongoose.model('User', userSchema);

  // Aggregation to find average age
  User.aggregate([
    { $group: { _id: null, avgAge: { $avg: '$age' } } }
  ]).then(result => console.log('Average age:', result[0].avgAge));

Best Practices/Pitfalls to Avoid 

Best Practices: Use aggregation for complex queries, optimize pipelines, and test aggregation performance.

Pitfalls to Avoid: Avoid overly complex aggregation pipelines that can degrade performance and ensure proper indexing.


Conclusion


This detailed cheat sheet provides a comprehensive overview of essential topics in Node.js, Express.js, and MongoDB, including definitions, usage, best practices, pitfalls to avoid, and relevant code snippets. This should serve as a valuable resource for revision and quick reference.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article