Page Content

Tutorials

What is the Purpose of Mongoose in a Node.js Application?

Mongoose in a Node.js

For MongoDB, Mongoose is an Object Data Modelling (ODM) library made especially for Node.js. It essentially serves as a link between your MongoDB database and Node.js application, offering a more organised and user-friendly method of working with your data.

Although MongoDB is a “schema-less” NoSQL database, which means that you don’t need to give your documents a strict structure, this flexibility can occasionally result in irregularities or make maintaining large scale applications more challenging. In order to solve this, Mongoose introduces a schema-based methodology to your application layer.

Connecting to MongoDB with Mongoose

You must install Mongoose using npm in order to begin using it: npm install mongoose. Mongoose.connect() can be used to connect to your MongoDB database after it has been installed. It requires a connection URL that usually contains the database name, port (e.g., 27017), and database server (e.g., localhost). Additionally, you can set options like useCreateIndex: true and useNewUrlParser: true. To control the quantity of connections, Mongoose additionally lets you provide connection parameters like poolSize. You may utilise the open and error events from the mongoose.connection object to see if the connection was successful.

Reading Data (Querying Documents) Mongoose offers simple ways to read information from your collections:

  1. Model.find(query, callback): To retrieve several documents that match a given query, use the Model.find(query, callback) function.
    • The query will return all documents in the collection if you give an empty object {}.
    • By supplying an object containing key-value pairs, you can filter documents (for example, { completed: false } to find unfinished jobs).
    • Unlike the cursors in the native MongoDB driver, Mongoose queries return an array of documents directly, making data use easier.
    • $text and $search MongoDB operators can be used in your find query for more complex text searches, usually after a text index has been created on the pertinent field.
    • You can limit the amount of documents returned by chaining methods like .limit(n) (e.g., .limit(5)).
    • .lean() can be used to reduce complexity and overhead by removing parts of the raw BSON properties, which is helpful but not necessary.
  2. Model.findOne(query, callback): To retrieve a single document that corresponds to the query that was supplied.
  3. Model.findById(id, callback): To locate a single document by its _id, use the Model.findById(id, callback) method. When searching by ID, keep in mind that if you’re using the native driver, you may need to use new ObjectID("your_id_string") to convert a string ID to an ObjectID, but Mongoose usually takes care of this automatically.
  4. When working with promises, you can manage results and errors by using .exec() after find(), followed by a chain of .then() and .catch().

Updating Data Mongoose makes document updates easier with these techniques:

  • Model.updateOne(filter, update, options, callback): Modifies a single document that satisfies the filter requirements (filter, update, options, callback).
  • Model.updateMany(filter, update, options, callback): Modifies several documents that meet the filter requirements (filter, update, options, callback).
  • Model.update(): A typical approach for changing one or more documents is Model.update().
  • Model.replaceOne(): Generates a new document in lieu of the first matching one.
  • The update argument specifies the modifications to apply, often using MongoDB update operators like:
    • $inc: Increments a numeric field (e.g., $inc: { age: 1 }).
    • $set: Sets the value of a field (e.g., $set: { completed: true }).
  • Model.findByIdAndUpdate(id, updates, options): Using the document’s ID, Model.findByIdAndUpdate(id, updates, options) locates the document and applies the changes. Commonly used options include new: true (which returns the revised document) and runValidators: true (which runs schema validators on the updates). Try/catch for errors is one way to deal with this in an async/await block.

Eliminating Information In order to use Mongoose to eliminate documents from your MongoDB collections:

  1. Deletes a single document that matches the given filter using Model.deleteOne(filter, options, callback).
  2. The function Model.deleteMany(filter, options, callback) eliminates every document that matches the defined filter.
  3. Model.remove(filter, callback): You can also use this method to remove documents.
  4. Model.findByIdAndDelete(id) can be used to remove a single document by ID.
  5. Cascade deletes, which include automatically removing all tasks linked to a person when their account is deleted, can be accomplished with Mongoose middleware. Pre('remove') hooks on the schema are frequently used to accomplish this.

Data Sanitisation and Validation With Mongoose, you can guarantee data integrity by defining validation and sanitisation rules from inside your schemas. Thus, user data is standardised and the types of data that can be saved are limited.

  • Schema Type Options: Mongoose offers built-in validation choices right in the schema definition:
    • required: true: It is Guarantees that a field has a value entered.
    • trim: true: Gets rid of whitespace at the start and finish of string values.
    • lowercase: true: Prior to storing, string values are converted to lowercase using the lowercase option.
    • unique: true: Guarantees that a field’s value is distinct throughout the collection (e.g., for usernames or emails).
  • Custom Validation: A schema field’s validate property can be used to implement custom validation functions. This function receives the value to validate and should throw an Error if the data is invalid.
    • Common checks like isEmail() can be performed using external libraries like validator, which can be installed using npm i validator, in bespoke validation routines.
  • Schema Defaults: The _id (of type ObjectId) and __v (or versionKey) fields are automatically added to documents by Mongoose by default.
    • An identifier that is unique is the _id field. Setting _id: false in the schema settings will disable it.
    • The __v field keeps track of the document’s internal revision. VersionKey: false can be used in the schema settings to turn it off.
  • Compound Indexes: These exist at the schema level and allow you to establish indexes on several columns (e.g., usersSchema.index({username: 1, email: 1})).
  • autoIndex: Mongoose calls ensureIndex for every index by default; however, in MongoDB 3.0.0+, ensureIndex is no longer used. It is advised that you stop this behaviour by setting autoIndex: false on your connection or schema in order to prevent any possible performance issues.
  • Mongoose Middleware (Pre-Hooks): The Mongoose Middleware (Pre-Hooks) allows middleware methods (like save and remove) to execute either before or after a model lifecycle event. This is effective for jobs such as:
    • Hashing Passwords: It is possible to ensure that passwords are never stored in plain text by utilising a pre('save') hook to automatically hash a user’s password using a library such as bcrypt before the user document is saved to the database.

Developers may efficiently manage their data by utilising these Mongoose features, guaranteeing consistency and integrity across all of their Node.js apps.

Index