• Stars
    star
    26,622
  • Rank 702 (Top 0.02 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 14 years ago
  • Updated 5 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

MongoDB object modeling designed to work in an asynchronous environment.

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 7.0.0 was released on February 27, 2023. You can find more details on backwards breaking changes in 7.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/[email protected]/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 <[email protected]>

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.

More Repositories

1

wp-calypso

The JavaScript and API powered WordPress.com
JavaScript
12,359
star
2

_s

Hi. I'm a starter theme called _s, or underscores, if you like. I'm a theme meant for hacking so don't use me as a Parent Theme. Instead try turning me into the next, most awesome, WordPress theme out there. That's what I'm here for.
CSS
10,849
star
3

node-canvas

Node canvas is a Cairo backed Canvas implementation for NodeJS.
JavaScript
9,820
star
4

kue

Kue is a priority job queue backed by redis, built for node.js.
JavaScript
9,434
star
5

simplenote-electron

Simplenote for Web, Windows, and Linux
TypeScript
4,517
star
6

juice

Juice inlines CSS stylesheets into your HTML source.
JavaScript
3,037
star
7

pocket-casts-android

Pocket Casts Android 🎧
Kotlin
2,440
star
8

cli-table

Pretty unicode tables for the CLI with Node.JS
JavaScript
2,243
star
9

expect.js

Minimalistic BDD-style assertions for Node.JS and the browser.
JavaScript
2,098
star
10

simplenote-ios

Simplenote for iOS
Swift
1,976
star
11

monk

The wise MongoDB API
JavaScript
1,845
star
12

knox

S3 Lib
JavaScript
1,738
star
13

simplenote-android

Simplenote for Android
Java
1,688
star
14

jetpack

Security, performance, marketing, and design tools — Jetpack is made by WordPress experts to make WP sites safer and faster, and help you grow your traffic.
PHP
1,550
star
15

pocket-casts-ios

Pocket Casts iOS app 🎧
Swift
1,464
star
16

simplenote-macos

Simplenote for macOS
Swift
1,420
star
17

antiscroll

OS X Lion style cross-browser native scrolling on the web that gets out of the way.
JavaScript
1,079
star
18

wp-desktop

WordPress.com for Desktop
981
star
19

WP-Job-Manager

Manage job listings from the WordPress admin panel, and allow users to post jobs directly to your site.
PHP
874
star
20

browser-repl

Launch a repl on your command line to any browser in the cloud.
JavaScript
728
star
21

themes

Free WordPress themes made by Automattic for WordPress.org and WordPress.com.
CSS
693
star
22

legalmattic

Democratizing WordPress.com legalese since 2014!
672
star
23

wpcom.js

WordPress.com JavaScript API client designed for Node.js and browsers
JavaScript
658
star
24

Picard

A prototype theme that uses React and WP-API
CSS
631
star
25

fb-instant-articles

Archived (see Readme). Enable Facebook Instant Articles on your WordPress site.
PHP
628
star
26

sensei

Sensei LMS - Online Courses, Quizzes, & Learning
PHP
514
star
27

developer

In your WordPress, developing locally
PHP
470
star
28

wordpress-activitypub

ActivityPub for WordPress
PHP
442
star
29

theme-components

A collection of patterns for creating a custom starter WordPress theme.
PHP
404
star
30

wp-super-cache

WP Super Cache: A fast caching engine for WordPress
PHP
399
star
31

Edit-Flow

WordPress plugin to accelerate your editorial workflow
PHP
341
star
32

o2

The o2 plugin for WordPress — blogging at the speed of thought
JavaScript
332
star
33

newspack-plugin

An advanced open-source publishing and revenue-generating platform for news organizations.
PHP
310
star
34

liveblog

Liveblogging done right. Using WordPress.
PHP
304
star
35

batcache

A memcached HTML page cache for WordPress.
PHP
278
star
36

Co-Authors-Plus

Multiple bylines and Guest Authors for WordPress
PHP
275
star
37

newspack-theme

A theme for Newspack.
PHP
265
star
38

vip-quickstart

Retired
PHP
265
star
39

Iris

A(n awesome) Color Picker
JavaScript
257
star
40

babble

Multilingual WordPress done right.
PHP
244
star
41

syntaxhighlighter

WordPress plugin that makes it easy to post syntax-highlighted code snippets.
CSS
237
star
42

VIP-Coding-Standards

PHP_CodeSniffer ruleset to enforce WordPress VIP coding standards.
PHP
210
star
43

underscores.me

PHP
209
star
44

newspack-blocks

Gutenberg blocks for the Newspack project.
PHP
193
star
45

isolated-block-editor

Repackages Gutenberg's editor playground as a full-featured multi-instance editor that does not require WordPress.
CSS
192
star
46

custom-metadata

A WordPress plugin that provides an easy way to add custom fields to your object types (post, pages, custom post types, users)
PHP
191
star
47

camptix

Moved to https://github.com/WordPress/wordcamp.org/
PHP
182
star
48

browserbuild

JavaScript
170
star
49

woocommerce-payments

Accept payments via credit card. Manage transactions within WordPress.
PHP
162
star
50

vip-go-mu-plugins

The development repo for mu-plugins used on the WordPress VIP Platform.
PHP
158
star
51

Documattic

WordPress presentations and resources shared by WordPress.com VIP
JavaScript
156
star
52

google-docs-add-on

Publish to WordPress from Google Docs
JavaScript
152
star
53

mydb

JavaScript
150
star
54

vip-scanner

Deprecated: Scan all sorts of themes and files and things! Use PHPCS and the VIP coding standards instead
PHP
140
star
55

wp-memcached

Memcached Object Cache for WordPress.
PHP
139
star
56

Genericons

A public mirror of changes to the Genericon release.
CSS
136
star
57

regenerate-thumbnails

WordPress plugin for regenerating thumbnails of uploaded images. Over 1 million active users and counting.
PHP
131
star
58

media-explorer

With Media Explorer, you can now search for tweets and videos on Twitter and YouTube directly from the Add Media screen in WordPress.
PHP
124
star
59

Rewrite-Rules-Inspector

WordPress plugin to inspect your rewrite rules.
PHP
123
star
60

PhpStorm-Resources

PhpStorm is making inroads at Automattic. Here you'll find various helpful files we've made.
123
star
61

wordbless

WorDBless allows you to use WordPress core functions in your PHPUnit tests without having to set up a database and the whole WordPress environment
PHP
122
star
62

vip-go-mu-plugins-built

The generated repo for mu-plugins used on the VIP Go platform.
PHP
120
star
63

social-logos

A repository of all the social logos we use on WordPress.com
JavaScript
119
star
64

Cron-Control

A fresh take on running WordPress's cron system, allowing parallel processing
PHP
116
star
65

block-experiments

A monorepo of Block Experiments
JavaScript
114
star
66

genericons-neue

Genericons Neue are generic looking icons, suitable for a blog or simple website
HTML
114
star
67

nginx-http-concat

WordPress plugin to perform CSS and JavaScript concatenation of individual script files into one resource request.
PHP
114
star
68

php-thrift-sql

A PHP library for connecting to Hive or Impala over Thrift
PHP
113
star
69

wp-e2e-tests

Automated end-to-end tests for WordPress.com
JavaScript
112
star
70

ad-code-manager

Easily manage the ad codes that need to appear in your templates
PHP
112
star
71

gridicons

The WordPress.com icon set
PHP
108
star
72

woocommerce-services

WooCommerce Services is a feature plugin that integrates hosted services into WooCommerce (3.0+), and currently includes automated tax rates and the ability to purchase and print USPS shipping labels.
JavaScript
104
star
73

es-backbone

ElasticSearch Backbone library for quickly building Faceted Search front ends.
JavaScript
103
star
74

syndication

Syndicate your WordPress content.
PHP
102
star
75

theme-tools

Tools for making better themes, better.
JavaScript
99
star
76

mShots

Website Thumbnail/Snapshot Service
JavaScript
94
star
77

prefork

PHP class for pre-loading heavy PHP apps before serving requests
PHP
94
star
78

phpcs-neutron-standard

A set of phpcs sniffs for PHP >7 development
PHP
93
star
79

newspack-newsletters

Author email newsletters in WordPress
PHP
89
star
80

musictheme

A theme for bands and musicians that uses an experimental Gutenberg layout.
CSS
89
star
81

gutenberg-themes-sketch

A set of Sketch files to help you design block-driven WordPress themes.
88
star
82

zoninator

Curation made easy! Create "zones" then add and order your content straight from the WordPress Dashboard.
PHP
85
star
83

cloudup-cli

cloudup command-line executable
JavaScript
83
star
84

go-search-replace

🚀 Search & replace URLs in WordPress SQL files.
Go
81
star
85

lazy-load

Lazy load images on your WordPress site to improve page load times and server bandwidth.
JavaScript
77
star
86

gutenberg-ramp

Control conditions under which Gutenberg loads - either from your theme code or from a UI
PHP
75
star
87

measure-builds-gradle-plugin

Gradle Plugin for reporting build time metrics.
Kotlin
74
star
88

auto-update

Objective-C
73
star
89

wpes-lib

WordPress-Elasticsearch Lib
PHP
73
star
90

vip-go-skeleton

The base repository structure for all VIP Go sites
PHP
72
star
91

msm-sitemap

Comprehensive sitemaps for your WordPress VIP site. Joint collaboration between Metro.co.uk, WordPress VIP, Alley Interactive, Maker Media, 10up, and others.
PHP
70
star
92

jurassic.ninja

A frontend to launching ephemeral WordPress instances that auto-destroy after some time
PHP
69
star
93

gutenberg-block-styles

An example of a simple plugin that adds a block style to Gutenberg.
PHP
68
star
94

atd-chrome

After the Deadline extension for Chrome
JavaScript
66
star
95

wp-api-console

WordPress (.com and .org) API Console written in React/Redux
JavaScript
66
star
96

eventbrite-api

The Eventbrite API plugin brings the power of Eventbrite to WordPress, for both users and developers.
PHP
65
star
97

mongo-query

mongo query API component
JavaScript
65
star
98

site-logo

Add a logo to your WordPress site. Set it once, and all themes that support it will display it automatically.
PHP
65
star
99

vip-go-nextjs-skeleton

A Next.js boilerplate for decoupled WordPress on VIP.
TypeScript
65
star
100

newspack-popups

AMP-compatible popup notifications.
PHP
61
star