Convert Figma logo to code with AI

Automattic logomongoose

MongoDB object modeling designed to work in an asynchronous environment.

26,901
3,833
26,901
241

Top Related Projects

The official MongoDB Node.js driver

34,121

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

29,432

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

38,831

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

A simple Node.js ORM for PostgreSQL, MySQL and SQLite3 built on top of Knex.js

19,158

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

Quick Overview

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward, schema-based solution to model application data and includes built-in type casting, validation, query building, and business logic hooks.

Pros

  • Provides a schema-based solution for modeling MongoDB data
  • Offers built-in data validation and type casting
  • Supports middleware (pre/post hooks) for better control over data operations
  • Includes a powerful query API for complex data retrieval

Cons

  • Can be slower than native MongoDB driver for simple operations
  • Adds an extra layer of abstraction, which may not be necessary for all projects
  • Learning curve for developers new to ODMs or coming from SQL backgrounds
  • Some complex queries may be more efficient when written directly in MongoDB

Code Examples

  1. Defining a schema and model:
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: String,
  email: { type: String, required: true, unique: true },
  age: { type: Number, min: 18 }
});

const User = mongoose.model('User', userSchema);
  1. Creating and saving a document:
const newUser = new User({
  name: 'John Doe',
  email: 'john@example.com',
  age: 25
});

await newUser.save();
  1. Querying documents:
// Find all users older than 21
const adults = await User.find({ age: { $gt: 21 } });

// Find one user by email
const user = await User.findOne({ email: 'john@example.com' });
  1. Using middleware:
userSchema.pre('save', function(next) {
  if (this.isModified('password')) {
    this.password = hashPassword(this.password);
  }
  next();
});

Getting Started

  1. Install Mongoose:

    npm install mongoose
    
  2. Connect to MongoDB:

    const mongoose = require('mongoose');
    await mongoose.connect('mongodb://localhost/myapp', {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    
  3. Define a schema and model:

    const catSchema = new mongoose.Schema({
      name: String,
      age: Number
    });
    const Cat = mongoose.model('Cat', catSchema);
    
  4. Create and save a document:

    const kitty = new Cat({ name: 'Whiskers', age: 3 });
    await kitty.save();
    console.log('Meow!');
    

Competitor Comparisons

The official MongoDB Node.js driver

Pros of node-mongodb-native

  • Lower-level API providing more direct control over MongoDB operations
  • Potentially better performance due to less abstraction
  • Closer to native MongoDB query syntax, easier transition for those familiar with MongoDB

Cons of node-mongodb-native

  • More verbose code required for common operations
  • Lack of built-in schema validation and middleware support
  • Steeper learning curve for developers new to MongoDB

Code Comparison

Mongoose:

const User = mongoose.model('User', { name: String, age: Number });
const user = new User({ name: 'John', age: 30 });
await user.save();

node-mongodb-native:

const collection = db.collection('users');
await collection.insertOne({ name: 'John', age: 30 });

Key Differences

  • Mongoose provides an Object Document Mapper (ODM) with schema definition and validation
  • node-mongodb-native offers a more direct interface to MongoDB operations
  • Mongoose includes features like middleware, population, and plugins
  • node-mongodb-native requires manual handling of connections and collections

Use Cases

  • Choose Mongoose for applications requiring structured data models and validation
  • Opt for node-mongodb-native when needing fine-grained control over MongoDB operations or working with dynamic schemas
34,121

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

Pros of TypeORM

  • Supports multiple databases (SQL and NoSQL) with a single API
  • Provides both Active Record and Data Mapper patterns
  • Offers advanced features like migrations and schema synchronization

Cons of TypeORM

  • Steeper learning curve, especially for developers new to ORMs
  • Less mature ecosystem compared to Mongoose
  • Performance can be slower for complex queries

Code Comparison

Mongoose:

const UserSchema = new Schema({
  name: String,
  email: { type: String, required: true, unique: true },
  age: Number
});

const User = mongoose.model('User', UserSchema);

TypeORM:

@Entity()
class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column({ unique: true })
  email: string;

  @Column()
  age: number;
}

Summary

TypeORM offers more flexibility with database support and patterns, but comes with a steeper learning curve. Mongoose is more specialized for MongoDB and has a larger ecosystem. The choice between them depends on project requirements and developer preferences.

29,432

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

Pros of Sequelize

  • Supports multiple databases (PostgreSQL, MySQL, SQLite, and Microsoft SQL Server)
  • Provides more robust and flexible querying capabilities
  • Offers built-in migration and seeding tools

Cons of Sequelize

  • Steeper learning curve due to more complex API
  • Can be slower for simple operations compared to Mongoose
  • Requires more setup and configuration

Code Comparison

Mongoose:

const User = mongoose.model('User', {
  name: String,
  email: String
});

const user = new User({ name: 'John', email: 'john@example.com' });
await user.save();

Sequelize:

const User = sequelize.define('User', {
  name: DataTypes.STRING,
  email: DataTypes.STRING
});

const user = await User.create({ name: 'John', email: 'john@example.com' });

Both Mongoose and Sequelize are popular Object-Relational Mapping (ORM) libraries for Node.js, but they serve different purposes. Mongoose is specifically designed for MongoDB, while Sequelize supports multiple SQL databases. Sequelize offers more flexibility in terms of database choice and advanced querying capabilities, but it comes with a steeper learning curve. Mongoose, on the other hand, provides a simpler API and is optimized for MongoDB, making it easier to get started with NoSQL databases.

38,831

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

Pros of Prisma

  • Type-safe database access with auto-generated TypeScript types
  • Intuitive and powerful query API with better performance optimization
  • Supports multiple databases (PostgreSQL, MySQL, SQLite, MongoDB)

Cons of Prisma

  • Steeper learning curve for developers familiar with traditional ORMs
  • Less flexibility for complex queries compared to raw SQL or Mongoose

Code Comparison

Prisma:

const user = await prisma.user.create({
  data: { name: 'Alice', email: 'alice@example.com' },
})

Mongoose:

const user = await User.create({
  name: 'Alice',
  email: 'alice@example.com',
})

Key Differences

  • Prisma uses a schema file to define models, while Mongoose uses JavaScript objects
  • Prisma generates a type-safe client, whereas Mongoose relies on runtime checks
  • Prisma offers better performance for complex queries due to its query engine
  • Mongoose has a larger ecosystem and more mature codebase

Use Cases

  • Prisma: Modern TypeScript projects, applications requiring type safety
  • Mongoose: Node.js projects with MongoDB, applications needing flexible schemas

Both ORMs have their strengths, and the choice depends on project requirements, database preferences, and development team expertise.

A simple Node.js ORM for PostgreSQL, MySQL and SQLite3 built on top of Knex.js

Pros of Bookshelf

  • More flexible with database choices, supporting PostgreSQL, MySQL, and SQLite3
  • Provides a more lightweight ORM solution with less overhead
  • Offers a plugin system for extending functionality

Cons of Bookshelf

  • Smaller community and ecosystem compared to Mongoose
  • Less comprehensive documentation and fewer learning resources
  • Requires more manual setup and configuration

Code Comparison

Mongoose:

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  age: Number
});

const User = mongoose.model('User', userSchema);

Bookshelf:

const User = bookshelf.Model.extend({
  tableName: 'users',
  hasTimestamps: true
});

Both Mongoose and Bookshelf are popular Object-Relational Mapping (ORM) libraries for Node.js, but they cater to different database types and use cases. Mongoose is specifically designed for MongoDB, providing a schema-based solution with built-in type casting, validation, and middleware support. Bookshelf, on the other hand, is more flexible and works with SQL databases, offering a simpler API for defining models and relationships.

Mongoose excels in its robust feature set, extensive documentation, and large community support. It's particularly well-suited for projects using MongoDB and requiring complex data modeling. Bookshelf shines in its simplicity and adaptability to various SQL databases, making it a good choice for developers who prefer working with relational databases or need to support multiple database types in their projects.

19,158

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

Pros of Knex

  • Supports multiple database systems (PostgreSQL, MySQL, SQLite3, etc.)
  • Provides a powerful query builder for complex SQL operations
  • Offers migration and seeding tools for database schema management

Cons of Knex

  • Steeper learning curve compared to Mongoose's simpler API
  • Lacks built-in schema validation and middleware support
  • Requires more manual setup for relationships between tables

Code Comparison

Mongoose:

const userSchema = new mongoose.Schema({
  name: String,
  email: { type: String, required: true, unique: true },
  age: Number
});

const User = mongoose.model('User', userSchema);

Knex:

knex.schema.createTable('users', table => {
  table.increments('id');
  table.string('name');
  table.string('email').notNullable().unique();
  table.integer('age');
});

Mongoose provides a more declarative approach to defining schemas and models, while Knex offers a lower-level API for creating database tables and performing queries. Mongoose abstracts away much of the database complexity, making it easier to work with MongoDB, while Knex gives developers more control over SQL operations across various database systems.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Mongoose

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports Node.js and Deno (alpha).

Build Status NPM version Deno version Deno popularity

npm

Documentation

The official documentation website is mongoosejs.com.

Mongoose 8.0.0 was released on October 31, 2023. You can find more details on backwards breaking changes in 8.0.0 on our docs site.

Support

Plugins

Check out the plugins search site to see hundreds of related modules from the community. Next, learn how to write your own plugin from the docs or this blog post.

Contributors

Pull requests are always welcome! Please base pull requests against the master branch and follow the contributing guide.

If your pull requests makes documentation changes, please do not modify any .html files. The .html files are compiled code, so please make your changes in docs/*.pug, lib/*.js, or test/docs/*.js.

View all 400+ contributors.

Installation

First install Node.js and MongoDB. Then:

npm install mongoose

Mongoose 6.8.0 also includes alpha support for Deno.

Importing

// Using Node.js `require()`
const mongoose = require('mongoose');

// Using ES6 imports
import mongoose from 'mongoose';

Or, using Deno's createRequire() for CommonJS support as follows.

import { createRequire } from 'https://deno.land/std@0.177.0/node/module.ts';
const require = createRequire(import.meta.url);

const mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/test')
  .then(() => console.log('Connected!'));

You can then run the above script using the following.

deno run --allow-net --allow-read --allow-sys --allow-env mongoose-test.js

Mongoose for Enterprise

Available as part of the Tidelift Subscription

The maintainers of mongoose and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Overview

Connecting to MongoDB

First, we need to define a connection. If your app uses only one database, you should use mongoose.connect. If you need to create additional connections, use mongoose.createConnection.

Both connect and createConnection take a mongodb:// URI, or the parameters host, database, port, options.

await mongoose.connect('mongodb://127.0.0.1/my_database');

Once connected, the open event is fired on the Connection instance. If you're using mongoose.connect, the Connection is mongoose.connection. Otherwise, mongoose.createConnection return value is a Connection.

Note: If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed.

Important! Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc.

Defining a Model

Models are defined through the Schema interface.

const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

const BlogPost = new Schema({
  author: ObjectId,
  title: String,
  body: String,
  date: Date
});

Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:

The following example shows some of these features:

const Comment = new Schema({
  name: { type: String, default: 'hahaha' },
  age: { type: Number, min: 18, index: true },
  bio: { type: String, match: /[a-z]/ },
  date: { type: Date, default: Date.now },
  buff: Buffer
});

// a setter
Comment.path('name').set(function(v) {
  return capitalize(v);
});

// middleware
Comment.pre('save', function(next) {
  notify(this.get('email'));
  next();
});

Take a look at the example in examples/schema/schema.js for an end-to-end example of a typical setup.

Accessing a Model

Once we define a model through mongoose.model('ModelName', mySchema), we can access it through the same function

const MyModel = mongoose.model('ModelName');

Or just do it all at once

const MyModel = mongoose.model('ModelName', mySchema);

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name. For example, if you use

const MyModel = mongoose.model('Ticket', mySchema);

Then MyModel will use the tickets collection, not the ticket collection. For more details read the model docs.

Once we have our model, we can then instantiate it, and save it:

const instance = new MyModel();
instance.my.key = 'hello';
await instance.save();

Or we can find documents from the same collection

await MyModel.find({});

You can also findOne, findById, update, etc.

const instance = await MyModel.findOne({ /* ... */ });
console.log(instance.my.key); // 'hello'

For more details check out the docs.

Important! If you opened a separate connection using mongoose.createConnection() but attempt to access the model through mongoose.model('ModelName') it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:

const conn = mongoose.createConnection('your connection string');
const MyModel = conn.model('ModelName', schema);
const m = new MyModel();
await m.save(); // works

vs

const conn = mongoose.createConnection('your connection string');
const MyModel = mongoose.model('ModelName', schema);
const m = new MyModel();
await m.save(); // does not work b/c the default connection object was never connected

Embedded Documents

In the first example snippet, we defined a key in the Schema that looks like:

comments: [Comment]

Where Comment is a Schema we created. This means that creating embedded documents is as simple as:

// retrieve my model
const BlogPost = mongoose.model('BlogPost');

// create a blog post
const post = new BlogPost();

// create a comment
post.comments.push({ title: 'My comment' });

await post.save();

The same goes for removing them:

const post = await BlogPost.findById(myId);
post.comments[0].deleteOne();
await post.save();

Embedded documents enjoy all the same features as your models. Defaults, validators, middleware.

Middleware

See the docs page.

Intercepting and mutating method arguments

You can intercept method arguments via middleware.

For example, this would allow you to broadcast changes about your Documents every time someone sets a path in your Document to a new value:

schema.pre('set', function(next, path, val, typel) {
  // `this` is the current Document
  this.emit('set', path, val);

  // Pass control to the next pre
  next();
});

Moreover, you can mutate the incoming method arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to next:

schema.pre(method, function firstPre(next, methodArg1, methodArg2) {
  // Mutate methodArg1
  next('altered-' + methodArg1.toString(), methodArg2);
});

// pre declaration is chainable
schema.pre(method, function secondPre(next, methodArg1, methodArg2) {
  console.log(methodArg1);
  // => 'altered-originalValOfMethodArg1'

  console.log(methodArg2);
  // => 'originalValOfMethodArg2'

  // Passing no arguments to `next` automatically passes along the current argument values
  // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)`
  // and also equivalent to, with the example method arg
  // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')`
  next();
});

Schema gotcha

type, when used in a schema has special meaning within Mongoose. If your schema requires using type as a nested property you must use object notation:

new Schema({
  broken: { type: Boolean },
  asset: {
    name: String,
    type: String // uh oh, it broke. asset will be interpreted as String
  }
});

new Schema({
  works: { type: Boolean },
  asset: {
    name: String,
    type: { type: String } // works. asset is an object with a type property
  }
});

Driver Access

Mongoose is built on top of the official MongoDB Node.js driver. Each mongoose model keeps a reference to a native MongoDB driver collection. The collection object can be accessed using YourModel.collection. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one notable exception that YourModel.collection still buffers commands. As such, YourModel.collection.find() will not return a cursor.

API Docs

Find the API docs here, generated using dox and acquit.

Related Projects

MongoDB Runners

Unofficial CLIs

Data Seeding

Express Session Stores

License

Copyright (c) 2010 LearnBoost <dev@learnboost.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

NPM DownloadsLast 30 Days