Understanding ORM/ODM libraries:

Understanding ORM/ODM libraries:

ORM and ODM are programming techniques that provide a higher-level abstraction for database interactions. They allows you to interact with databases using object oriented programming concepts, making database operations more automatic and less dependent on raw SQL queries.

? ORM (Object-Relational Mapping): Primarily used with relational databases, ORM translates between objects in code and rows in a relational database table.

? ODM (Object-Document Mapping): Built for NoSQL databases like MongoDB, ODM maps between objects in code and documents in a NoSQL database collection.

What is Mongoose?

Mongoose, a powerful MongoDB object modeling tool for Node.js, offers an elegant, schema-based solution for managing MongoDB databases. Its tight integration with Express.js positions it as the preferred choice for developers seeking an efficient approach to MongoDB interactions.

Use of Mongoose:

Mongoose takes away all the petty frustrations of working with MongoDB directly. With just a few lines of code, you can start building elegant schemas and models for your app data, with lots of great development features baked in. If you want to make your MongoDB experience as smooth as possible, Mongoose is the way to go!

Advantages of Mongoose :

? Easy translation between documents and JavaScript objects with its schema-based modeling

? Built-in type casting and validation to reduce errors

? Helper methods for common tasks like querying, updating records, etc.

? Easy connection handling for setting up MongoDB communication

? Additional features like middleware for interacting with data pre-save/post-save

? Object Data Modeling in MongoDB

? A huge benefit of using a NoSQL database like MongoDB is that you are not constrained to a rigid data model. You can add or remove fields, nest data multiple layers deep, and have a truly flexible data model that meets your needs today and can adapt to your ever-changing needs tomorrow. But being too flexible can also be a challenge. If there is no consensus on what the data model should look like, and every document in a collection contains vastly different fields, you're going to have a bad time.

? Mongoose Schema and Model

? On one end of the spectrum, we have ODM's like Mongoose, which from the get-go force us into a semi-rigid schema. With Mongoose, you would define a Schema object in your application code that maps to a collection in your MongoDB database. The Schema object defines the structure of the documents in your collection. Then, you need to create a Model object out of the schema. The model is used to interact with the collection.

Mongoose vs MongoDB Node.js Driver

The benefit of using Mongoose is that we have a schema to work against in our application code and an explicit relationship between our MongoDB documents and the Mongoose models within our application. The downside is that we can only create blog posts and they have to follow the above defined schema. If we change our Mongoose schema, we are changing the relationship completely, and if you're going through rapid development, this can greatly slow you down. The other downside is that this relationship between the schema and model only exists within the confines of our Node.js application. Our MongoDB database is not aware of the relationship, it just inserts or retrieves data it is asked for without any sort of validation. In the event that we used a different programming language to interact with our database, all the constraints and models we defined in Mongoose would be worthless. On the other hand, if we decided to use just the MongoDB Node.js driver, we could run queries against any collection in our database, or create new ones on the fly. The MongoDB Node.js driver does not have concepts of object data modeling or mapping. We simply write queries against the database and collection we wish to work with to accomplish the business goals.

Adding Schema Validation

We can choose between two different ways of adding schema validation to our MongoDB collections. The first is to use application-level validators, which are defined in the Mongoose schemas. The second is to use MongoDB schema validation, which is defined in the MongoDB collection itself. The huge difference is that native MongoDB schema validation is applied at the database level. Let's see why that matters by exploring both methods.

Schema Validation with Mongoose

When it comes to schema validation, Mongoose enforces it at the application layer as we've seen in the previous section. It does this in two ways. First, by defining our model, we are explicitly telling our Node.js application what fields and data types we'll allow to be inserted into a specific collection. For example, our Mongoose Blog schema defines a title property of type String . If we were to try and insert a blog post with a title property that was an array, it would fail. Anything outside of the defined fields, will also not be inserted in the database. Second, we further validate that the data in the defined fields matches our defined set of criteria. For example, we can expand on our Blog model by adding specific validators such as requiring certain fields, ensuring a minimum or maximum length for a specific field, or coming up with our custom logic even.

Let's see how this looks with Mongoose. In our code we would simply expand on the property and add our validators: Mongoose takes care of model definition and schema validation in one fell swoop. The downside though is still the same. These rules only apply at the application layer and MongoDB itself is none the wiser. The MongoDB Node.js driver itself does not have mechanisms for inserting or managing validations, and it shouldn't. We can define schema validation rules for our MongoDB database using the MongoDB Shell or Compass.

Similarities:

? Mongoose (ODM) and ORM provide a higher-level abstraction over the underlying database.

? They allow you to work with data in your application using a programming language (JavaScript in the case of Mongoose, and typically an object-oriented language like Java or Python in the case of ORM).

? They help handle the mapping between the application code and the database, making it easier to perform CRUD (Create, Read, Update, Delete) operations.

Differences:

? ORM is generally associated with relational databases (like MySQL, and PostgreSQL), whereas ODM is associated with NoSQL databases like MongoDB.

? The data models and structures in relational databases (tables, rows, columns) differ from those in NoSQL databases (documents, collections), so the mapping and concepts used by ORM and ODM can vary accordingly.

? MongoDB and Mongoose, being NoSQL and ODM, are schema-less by default, meaning that documents in a collection can have different fields. On the other hand, ORM systems often work with relational databases that enforce a predefined schema.

Key Features of Mongoose

1. Schema Definition: Mongoose allows you to define the schema for your MongoDB collections, giving your data structure and constraints. This schema definition is essential for data consistency and validation.

2. Validation: Mongoose provides built-in validation capabilities to ensure that data meets specific criteria before it’s stored in the database. You can use predefined validators or create custom validation functions.

3.Middleware: Mongoose supports middleware, enabling you to define functions that execute before or after certain operations, such as saving a document or removing it. This allows you to encapsulate domain specific logic in your data model.

4.Query Building: Mongoose simplifies the process of building complex queries for MongoDB. It provides a chainable API to create queries for finding, updating, and deleting documents.

5.Population: Mongoose allows you to populate referenced documents, making it easier to work with related data. This feature is particularly useful when dealing with relationships between documents. Schema Definition One of the key features of Mongoose is its ability to define schemas for your MongoDB collections.

The permitted Schema Types are:

? String

? Number

? Date

? Buffer

? Boolean

? Mixed

? ObjectId

? Array

? Decimal128

? Map

? UUID Ids

By default, Mongoose adds an id property to your schemas. When you create a new document with the automatically added id property, Mongoose creates a new _id of type ObjectId to your document.

要查看或添加评论,请登录

Cyclobold Tech的更多文章

社区洞察

其他会员也浏览了