Skip to content

Instantly share code, notes, and snippets.

@halitbatur
Created July 11, 2024 07:20
Show Gist options
  • Select an option

  • Save halitbatur/1d6bcff6f1eb5b78792d5402a9a20311 to your computer and use it in GitHub Desktop.

Select an option

Save halitbatur/1d6bcff6f1eb5b78792d5402a9a20311 to your computer and use it in GitHub Desktop.
Mongoose Discussion

Mongoose Discussion

  1. Explain the purpose of Mongoose middleware. How can you use pre and post hooks to manage data before and after certain operations? Provide examples of use cases where middleware would be beneficial in an Express.js application.
  2. How does Mongoose support indexing, and why is indexing important for database performance? Discuss how to create and use indexes in your schema and the impact they have on query efficiency.
  3. Describe the concept of schema methods in Mongoose. How do they differ from static methods, and when would you use each type? Give examples of scenarios where schema methods would enhance the functionality of your application.
  4. What are the advantages of using Mongoose’s built-in query helpers? How do they simplify the process of writing queries in an Express.js application? Discuss examples of custom query helpers you might create for a project.
  5. How does Mongoose handle relationships between different collections? Discuss the use of references and embedded documents, and compare their advantages and disadvantages in different scenarios.
@Gracepinkie
Copy link

Gracepinkie commented Jul 11, 2024

Sinethemba Zulu
Tumelo Thinane
Nonhlanhla Mazibuko

  1. Mongoose middleware serves as a mediator, intercepting and modifying operations within your Node.js application.

Pre-hooks allow you to execute custom code before a certain operation, such as saving or updating data, ensuring data validation.
Post-hooks are employed to handle actions after a specific operation, like sending notifications, logging changes, updating associated resources.

use cases: Authentication and Authorization : Use pre hooks to hash passwords before saving user data to the database and Use post hooks to log successful login attempts.

  1. Indexing is crucial for database performance as it helps in speeding up data retrieval operations by making the query process more efficient. By using indexes, databases can locate and fetch relevant data more quickly, resulting in quicker response times for queries.

` const mongoose = require('mongoose');

// Define your schema
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
createdAt: { type: Date, default: Date.now }
});

// Create an index on the email field
userSchema.index({ email: 1 }, { unique: true });

// Create the User model
const User = mongoose.model('User', userSchema); `

  1. in Mongoose, schema methods are functions that you can define on a schema. These methods are then available on the model instances (documents) created from that schema.

Schema methods are useful for encapsulating custom logic or behavior that you want to associate with your documents. They allow you to add custom functionality to your models, making your code more modular and maintainable.

an example of scenarios when to use the different scenarios

Static Methods:

User management: findAllUsers, createUser, updateUser, deleteUser
Batch operations: bulkUpdate, bulkDelete
Data aggregation:getAverageRating,getTotalSales

Instance Methods:

Validations: validatePassword, validateUniqueEmail
Document-level operations: generateUUID, calculateDerivedValue
Formatting/Transformation: formatName, toPublicJSON`

  1. Separation of concerns- separates data fetching logic from the rest of the application which makes the codebase more readable and easy to maintain. Mongoose built-in query helper allow us to define reusable code logic, which avoids code duplication, making the application less complex. Makes the code more readable by enclosing complex query logic within meaningful method names which allows us to reapply that logic across all queries. by encapsulating query logic, improving code readability and reusability, supporting method chaining, ensuring consistent business logic application, and simplifying unit testing. We can create a custom query helper to encapsulate some code logic that filters the data in some specified condition.

  2. Mongoose provides two main ways to handle relationships between different collections: references and embedded documents.

References:

Store ObjectIds to represent relationships
Flexible, scalable, but require additional queries
Embedded Documents:

Nested subdocuments in a single document
Fast data retrieval, ensure data consistency
Limited flexibility, size constraints
Choose based on:

One-to-one/many: Embedded better
Many-to-many: References better
Frequently accessed data: Embedded better
Large/growing data: References better
Data consistency needs: Embedded better

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment