Mongoose: A Smoother Way To Interact With Mongodb

February 16, 2024

What is mongoose?

mongoose is a popular NodeJS library for managing NoSQL mongoDB related documents and collections. it provides an API for modeling, validation and querying of documents.

Schemas

Mongoose allows us to define schemas, as in a skeleton for a collection of documents, using the function .model("collection name", schema) Mongoose enables us to reference different documents in the schema using their ID which can later be populated when querying the documents. Mongoose provides built-in support for validation of properties of documents.

CRUD Operations

Mongoose provides functions for CRUD operations:

  • Delete: Model.deleteMany(), Model.deleteOne()
  • Find: Model.find(), Model.findById()
  • Update: Model.findByIdAndUpdate(), Model.updateOne()
  • Replace: Model.replaceOne()
  • Others: Model.findOneAndDelete(), Model.findOneAndReplace(), etc.

These functions simplify CRUD operations on MongoDB collections, encapsulating complexity.

Important Query Parameters

the projection and options parameters are optional parameters that you can pass to certain query functions to customize the behavior of the query.

Projection:

Projection allows you to specify which fields you want to include or exclude from the query result. It helps in controlling the shape of the returned documents.

You can specify the fields to include or exclude by providing an object where the keys represent the field names, and the values represent whether to include (1) or exclude (0) the field.

For example:

  • { name: 1, age: 1 } - Includes only the name and age fields.
  • { _id: 0 } - Excludes the _id field.

If no projection is provided, by default, all fields are included in the query result.

Options:

Options allow you to configure additional behavior for the query, such as sorting, limiting the number of results, skipping documents, and more.

Common options include:

  • sort: Specifies the sorting order for the query results.
  • limit: Limits the number of documents returned by the query.
  • skip: Specifies the number of documents to skip before returning results.
  • lean: If set to true, returns plain JavaScript objects instead of Mongoose documents (useful for performance optimization).
  • populate: Specifies which document fields to populate with references from other collections.

Options are typically provided as an object where each key represents an option name and its value specifies the corresponding configuration.

Mongoose documentation