Skip to content

Instantly share code, notes, and snippets.

@muslemomar
Created April 23, 2024 11:30
Show Gist options
  • Save muslemomar/09e1ca58664b52425c7820fcfc284956 to your computer and use it in GitHub Desktop.
Save muslemomar/09e1ca58664b52425c7820fcfc284956 to your computer and use it in GitHub Desktop.
  1. What are the differences and connections between Mongoose schemas and models? How do they work together in an Express.js application?
  2. How does Mongoose handle data validation? Discuss the benefits of using Mongoose for data validation as opposed to doing it manually in your Express.js routes.
  3. What are virtuals in Mongoose? Discuss how and why you might use them in a project. Give examples of scenarios where virtuals can be particularly useful.
  4. What is population in Mongoose? How does it differ from simply storing object IDs in your documents? Discuss scenarios where population is beneficial and when it might be better to avoid it.
  5. How does Mongoose handle asynchronous operations? Discuss the role of promises and async/await in managing database interactions in an Express.js application.
@HalwestEast
Copy link

  1. Schema is the literal definition of tables, columns, indexes, relations, procedures and whatever. The data model is the conceptual specification of how data will be expressed
  2. Mongoose is a MongoDB object modeling and handling for a node. js environment. Mongoose Validation is essentially a customizable middleware that gets defined inside the SchemaType of Mongoose schema. It automatically fires off before a document is saved in the NoSQL DB
  3. Virtuals in Mongoose are a way to create a field in a Mongoose model that can be manipulated like any other field, but that does not actually get persisted to the database
  4. Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s)
  5. Basic Use. Async/await lets us write asynchronous code as if it were synchronous. This is especially helpful for avoiding callback hell when executing multiple async operations in sequence--a common scenario when working with Mongoose.

Members: Rafeef, Zainab Al-Najjar, Mohammed Nazar, Halwest.

@fawzitheprogrammer
Copy link

  1. Mongoose Schemas vs. Models: Schemas define the structure of documents, while models provide an interface to interact with the database based on those schemas.

  2. Mongoose and Data Validation: Mongoose provides built-in validation for schema fields, ensuring data integrity and reducing the need for manual validation in Express.js routes.

  3. Virtuals in Mongoose: Virtuals are computed properties that are not stored in the database, useful for combining or transforming data without altering the actual document.

  4. Population in Mongoose: Population is a way to reference documents in other collections, providing flexibility in querying and avoiding data duplication.

  5. Asynchronous Operations in Mongoose: Mongoose uses promises and async/await to handle asynchronous operations, ensuring smooth database interactions in Express.js applications.


  1. Shkar Gharib
  2. Fawzi Gharib
  3. Aya Hassan
  4. Omar Sardar
  5. Jwan Karim

@Maram-Qais
Copy link

Maram-Qais commented Apr 23, 2024

1-In Mongoose, schemas define the structure and rules of data, while models are constructors that use these schemas to interact with MongoDB. Together, in an Express.js application, schemas set up the data attributes, and models handle database operations like creating and reading documents based on these schemas.

2-Mongoose handles data validation by allowing you to set rules directly in schemas. This approach is more efficient than manual validation in Express.js routes, as it centralizes validation logic, reduces code duplication, and helps maintain data integrity.

3-
Virtuals in Mongoose are non-persistent properties that derive values from existing fields. They're useful for combining fields or calculating values dynamically, such as creating a full name from first and last names or calculating age from a birthdate. This helps keep the database lean and offloads computation to the application level, which is useful for frequently accessed computed values.
4-Population in Mongoose replaces paths in documents with data from other collections, acting like a join in SQL. It's more data-rich than just storing object IDs but can slow down queries, especially under high load or with deep populations. It's beneficial for integrating related data easily, like displaying user details with comments, but should be avoided in high-performance or large dataset scenarios to prevent query slowdowns.
5-Mongoose manages asynchronous operations using promises, enabling clean and efficient database interactions in Express.js applications. By returning promises for database actions, Mongoose allows developers to use async/await syntax in Express routes, simplifying the code by making it more readable and easier to maintain. This approach helps avoid callback hell, streamlines error handling, and improves the overall flow of asynchronous database operations.

with : -Yousra Yaarob , Papula Ali, helin tayeb

@candourist
Copy link

candourist commented Apr 23, 2024

  1. Schemas and Models

    • Schemas define a document's structure, fields and validation rules
    • Models provide an API for CRUD operations on documents in a collection via methods like .find(), .save(), etc
  2. Data Validation

    • Validation rules are defined within schemas
    • Mongoose runs validators before documents are inserted or updated to maintain data integrity
  3. Virtuals

    • Virtuals define non-persisted properties derived from other fields
    • They allow joining or transforming fields to reduce duplication and keep related data in sync
    • Example:
A User schema with firstName and lastName strings

const userSchema = new Schema({
firstName: String,
lastName: String
});

userSchema.virtual('fullName')
.get(function () {
return ${this.firstName} ${this.lastName};
});

##fullName is now a virtual that joins the two name fields##
##It isn't stored in the database##
##But keeps full name in sync as first/last names change##
  1. Population

    • Population embeds full referenced documents rather than just IDs
    • This avoids extra queries later to populate associated data in one query
  2. Asynchronous Operations

    • Mongoose uses promises to handle asynchronous database operations
    • Async/await allows asynchronous code to be written sequentially for simpler logic flow between queries and application code

    Room #6

  • Aween Ezzat
  • Ali Lazzadin
  • Sajad Ismael
  • Payam R.

@ibrahimmuhaned
Copy link

Ibrahim muhaned || Ahmed Sabah || didam goran || koshyar abdul rahman

  1. What are the differences and connections between Mongoose schemas and models? How do they work together in an Express.js application?

Schemas and Models:

  • Schemas define the structure of documents within a collection, including fields, types, defaults, and validation rules.
  • Models are compiled from schemas and are constructors for creating documents with properties and behaviors defined in the schema.
  • Working Together: Schemas define the structure, while models provide the interface for interacting with the database. In an Express.js application, schemas and models are typically defined in separate modules and then used in routes to perform database operations.
  1. How does Mongoose handle data validation? Discuss the benefits of using Mongoose for data validation as opposed to doing it manually in your Express.js routes.

Data Validation:

  • Mechanism: Mongoose validates data based on the schema definitions, enforcing rules like required fields, type checking, min/max values, and custom validators.
  • Benefits: Using Mongoose for data validation centralizes the validation logic within schema definitions, promoting code reusability, consistency, and maintainability. Additionally, Mongoose provides error handling mechanisms for easier management of validation errors.
  • Comparison: Manual validation in Express.js routes can lead to scattered validation logic, making code harder to maintain and increasing the likelihood of inconsistencies.
  1. What are virtuals in Mongoose? Discuss how and why you might use them in a project. Give examples of scenarios where virtuals can be particularly useful.

Virtuals in Mongoose:

  • Definition: Virtuals are additional fields for a document that are not persisted in the database but are computed from other fields.
  • Usage: Virtuals are used to derive values or format data without storing it in the database, enhancing the readability and organization of code.
  • Examples: Virtuals can be used to concatenate fields, format dates, perform calculations, or create composite keys. They are particularly useful in scenarios where computed properties are needed without affecting the underlying data.
  1. What is population in Mongoose? How does it differ from simply storing object IDs in your documents? Discuss scenarios where population is beneficial and when it might be better to avoid it.

Population in Mongoose:

  • Definition: Population is the process of automatically replacing specified paths in a document with document(s) from another collection.
  • Difference: Instead of storing object IDs directly in a document, population allows referencing documents in other collections and loading them on demand.
  • Benefits: Population improves data organization, reduces redundancy, and allows for more efficient querying, especially when dealing with relationships between multiple collections or large datasets.
  • Considerations: While population can enhance performance and data organization, overuse can lead to increased database queries and potential performance issues. It may be better to avoid population in scenarios where performance is critical, or where embedding documents provides better data locality.
  1. How does Mongoose handle asynchronous operations? Discuss the role of promises and async/await in managing database interactions in an Express.js application.

Asynchronous Operations in Mongoose:

  • Mechanism: Mongoose supports asynchronous operations through Promises or async/await syntax. Methods typically return Promises, allowing for sequential or parallel execution of database operations.
  • Promises vs. async/await: Both Promises and async/await can be used to manage asynchronous code in Mongoose. Promises offer a more traditional approach, while async/await provides cleaner and more readable syntax.
  • Role in Express.js: Promises and async/await simplify handling of asynchronous database interactions in Express.js routes, improving code readability and maintainability. They allow for non-blocking operations, ensuring efficient handling of requests.

@Dilan-Ahmed
Copy link

Ahmed Isam | Hana Abdulla | Hanan Islam | Dilan Ahmed

  1. We would say that Models are more constructor functions which represents MongoDB Collection. On the other hand, the Schema is more about the structure and shape of the Data in MongoDB.

  2. Mongoose handles data validation through already built in data validation features like Schema Validation through which Mongoose specify the data type ,required fields to be filled, Min/Max values also custom validation functions. Also, Mongoose has presaved Hooks that enables the developer to implement a validation logic that had been coded by him/her before the document being saved. Also, these points mentioned before are the benefits as well of using Mongoose. In express js we can validate the content of the data which might be having SQL injections or JS.

  3. In Mongoose, virtuals are additional fields that are not persisted in the database but are computed or derived from other fields in the document. They allow you to define virtual properties on your documents that can be accessed and used just like regular properties.

Virtuals in Mongoose are useful when you want to present data in a simpler way without the need of updating or changing the schema, an example would be having a schema user having firstName and LastName fields through virtual property we can have a fullName concatenations for the first and last names when you want it.

  1. Mongoose handles asynchronous operations primarily through the use of Promises or async/await syntax.

@0Rawan
Copy link

0Rawan commented Apr 23, 2024

Dawood AlKawaz, Teba Kaad, Elaf Gardi and Rawan Mustafa

  1. mongoose use async/await to execute queries accordingly and avoiding callback hell
    which also allow us to wait for response and display the predictable result
  2. Mongoose using the schema options provided like data types and other properties like unique, required or default to make sure that data are valid before saving the document
  3. Mongoose domains are not used for interaction with database directly instead it works by defining them and taking a specific value from the document to run a callback upon and return a result.
    This could be handy for example on an e-commerce website where you can get all the products in specific order to calculate the net price
  4. Mongoose population is a way to simply refer to documents on other collections, so when we add an ObjectId for example it will check the referenced collection if it has that document and not taking our word for granted
    It will consume complicated queries which will be a drawdown regarding the run time to query documents on multiple collections
  5. Mongoose use async/await to execute queries accordingly and avoiding callback hell
    which also allow us to wait for response and display the predictable result

@mawjaljadirjy
Copy link

1.

  • In Mongoose, a schema defines the structure of documents in a MongoDB collection, specifying fields, types, validators, etc.
  • A model is a compiled version of a schema, used to interact with MongoDB collections by creating, reading, updating, and deleting documents.
  • In an Express.js application, you define schemas using mongoose.Schema() and create models with mongoose.model().
  • Models are used within Express.js route handlers to perform CRUD operations on the database, based on the defined schemas.

2.

  • Mongoose handles data validation through schema-level validation rules defined using built-in and custom validators.
  • Built-in validators include required, min, max, enum, match, etc.
  • Custom validation functions can also be defined to enforce complex validation logic.
  • Mongoose automatically validates data against the schema rules when creating or updating documents, throwing validation errors if any rules are violated.
  • Benefits of using Mongoose for data validation include centralized logic, declarative syntax, automatic error handling, and integration with middleware, compared to manual validation in Express.js routes.

3.

  • Virtuals in Mongoose are computed properties defined on schemas that are not stored in the database.
  • They are defined using getters and setters and can be accessed like regular fields on documents.
  • Virtuals are useful for deriving properties, formatting data, performing aggregations, and enhancing data security in a project.
  • Examples include computing fullName, formatting dates, performing aggregate calculations, and maintaining data privacy.

4.

  • In Mongoose, population refers to automatically replacing specified paths in a document with actual documents from other collections by storing their ObjectIds.
  • It simplifies data retrieval, maintains data integrity, and reduces data duplication compared to simply storing ObjectIds.
  • Population is beneficial for managing one-to-many relationships, maintaining data integrity, and reducing data duplication.
  • However, it may introduce performance overhead, especially for high cardinality relationships, and may not be suitable for scenarios where embedded data is more efficient or performance-sensitive.

5.

  • Mongoose handles asynchronous operations using promises, which represent the eventual completion or failure of database operations.
  • Promises enable chaining of asynchronous operations and error handling using .then() and .catch().
  • Async/await syntax in Mongoose allows developers to write asynchronous code in a synchronous-looking manner, improving readability and maintainability.
  • In Express.js applications, promises or async/await can be used to manage database interactions within route handlers or middleware functions.
  • Benefits include readable code, simplified error handling, and sequential execution of asynchronous operations.

@amolllat
Copy link

Amal Mohammed

  1. A Mongoose schema is a blueprint that defines the structure of documents within a MongoDB collection. It defines the shape of the documents, including the fields and their types. Essentially, it outlines what each document in the collection will look like.
    A Mongoose model is a Models are responsible for creating, reading, updating, and deleting documents in the MongoDB database. They encapsulate all the database operations related to a particular collection.
    use them in an Express.js application 🅰️ Define Schemas. b: Create Models. c: Use Models in Route Handlers. In the Express.js application, schemas and models work together to manage data persistence.

  2. Data Validation in Mongoose: Mongoose provides built-in support for data validation using schema validators and This helps ensure data integrity and consistency in the application. Benefits of using Mongoose for data validation include code organization, reusability, and centralized management of validation rules. By defining validation rules in the schema, Mongoose automatically validates data before saving it to the database.

3)Virtuals in Mongoose: are document properties that are not stored in the MongoDB database but are computed on the fly. Virtuals are useful for deriving new properties from existing ones, performing computations, or formatting data. This helps ensure data integrity and consistency in the application. For example, you might use virtuals to calculate a user's full name from separate first and last name fields or to format dates in a specific way.

4)Population in Mongoose allows you to reference documents in other collections and automatically retrieve their contents. It replaces the stored IDs with actual document objects when querying. The population is beneficial for denormalizing data and simplifying queries by avoiding multiple database lookups. However, excessive use of population can lead to performance issues, so it's important to use it judiciously. In scenarios where performance is critical or when dealing with large datasets, it might be better to avoid population and manually manage references using IDs.
5) Mongoose uses Promises to handle asynchronous operations by default, but it also supports callbacks and async/await syntax. When interacting with the database, Mongoose methods return Promises that can be chained or handled using async/await.

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