Are you happy with your logging solution? Would you help us out by taking a 30-second survey? Click here

mongoose

MongoDB object modeling designed to work in an asynchronous environment.

Subscribe to updates I use mongoose


Statistics on mongoose

Number of watchers on Github 15080
Number of open issues 276
Average time to close an issue 6 days
Main language JavaScript
Average time to merge a PR 2 days
Open pull requests 61+
Closed pull requests 73+
Last commit over 1 year ago
Repo Created over 9 years ago
Repo Last Updated over 1 year ago
Size 38.3 MB
Homepage http://mongoosejs...
Organization / Authorautomattic
Latest Release4.0.2
Contributors243
Page Updated
Do you use mongoose? Leave a review!
View open issues (276)
View mongoose activity
View on github
Fresh, new opensource launches 🚀🚀🚀
Trendy new open source projects in your inbox! View examples

Subscribe to our mailing list

Evaluating mongoose for your project? Score Explanation
Commits Score (?)
Issues & PR Score (?)

Mongoose

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment.

Slack Status Build Status NPM version

Documentation

mongoosejs.com

Mongoose 5.0.0 was released on January 17, 2018. You can find more details on backwards breaking changes in 5.0.0 on GitHub.

Support

Importing

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

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

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

View all 300+ contributors. Stand up and be counted as a contributor too!

Installation

First install node.js and mongodb. Then:

$ npm install mongoose

Stability

The current stable branch is master. The 3.8.x branch contains legacy support for the 3.x release series, which is no longer under active development as of September 2015. The 3.8.x docs are still available.

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.

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/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,
    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.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 Mongoose will create the model for your tickets collection, not your ticket collection.

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

const instance = new MyModel();
instance.my.key = 'hello';
instance.save(function (err) {
  //
});

Or we can find documents from the same collection

MyModel.find({}, function (err, docs) {
  // docs.forEach
});

You can also findOne, findById, update, etc. 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;
m.save(); // works

vs

const conn = mongoose.createConnection('your connection string');
const MyModel = mongoose.model('ModelName', schema);
const m = new MyModel;
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
var BlogPost = mongoose.model('BlogPost');

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

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

post.save(function (err) {
  if (!err) console.log('Success!');
});

The same goes for removing them:

BlogPost.findById(myId, function (err, post) {
  if (!err) {
    post.comments[0].remove();
    post.save(function (err) {
      // do something
    });
  }
});

Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it's bubbled to the save() error callback, so error handling is a snap!

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:

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

// pre declaration is chainable
.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.

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.

mongoose open issues Ask a question     (View All Issues)
  • about 3 years transform option for cursor()
  • about 3 years .populate with separated ref not working
  • about 3 years possibility of async plugins
  • about 3 years Closing #4602 led to unexpected exception being thrown
  • about 3 years What is cached and what is not cached in mongoose?
  • about 3 years Why connect, createConnection, Connection#open? They overlap and conflict each other
  • about 3 years DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead
  • about 3 years QueryCursor#eachAsync uses O(N) stack frames.
  • about 3 years Referencing virtuals I get MissingSchemaError: Schema hasn't been registered for model
  • about 3 years populate array of ObjectId without ref, not work
  • about 3 years Aggregate cursor exec sometimes returns undefined?
  • about 3 years Save Array number coordinates
  • about 3 years Performance regression from 4.5.10 to 4.6.2
  • about 3 years Validation errors when using Node 7.0.0 with PM2
  • about 3 years Use prefixed internal properties to allow more freedom for schema path names
  • about 3 years Populate to string field isn't working
  • about 3 years enabling virtual populate in sub-doc schema results in `null` in find
  • about 3 years upgrade 3.8.25 to 4.6.6: big performance drop
  • about 3 years Select specific fields for Populating Virtuals
  • about 3 years Documentation on Handling Error
  • about 3 years How to set 'setCurrentLogger' as in the native driver
  • about 3 years Support node v7
  • about 3 years readPreference with secondaryPreferred not working with read command
  • about 3 years Cannot read property '$__' of undefined when defining default on property that has type of "array of embedded documents"
  • about 3 years Don't reconnect after disconnection
  • about 3 years mongoose.connect(uri, opts) does not return a promise
  • about 3 years (4.6.2 -> 4.6.3 regression) Calling .set on a subfield of a deselected subdoc wipes out other fields on the subdoc
  • about 3 years Randomly seeing high response time with findOne
  • about 3 years Cast to ObjectId failed for value "kitty" at path "_id" on some, not all, find queries
  • about 3 years [BUG] Array of references returned empty on discriminated schema when querying child schema.
mongoose open pull requests (View All Pulls)
  • Babel (WIP)
  • Once connection opens, function should have the parameters callback
  • repro; #3478
  • [Breaking] replace mongoose internal pluralize with pluralize package
  • Fix for #1766
  • Fix model version not being checked properly on queries with push operands. Issue #1898
  • Take 2: Ensure use of .hasOwnProperty() check when using for/in loops
  • [WIP] Multidimensional arrays
  • Allow setup timestamps by Schema.prototype.set
  • make ValidatorError.properties not enumerable
  • Make sure Document Exists, After we check to see is obj is an Object.
  • Allow saving of array fields selected via $elemMatch
  • aggregate promise #3946
  • Update mquery to 1.10
  • Updated QueryStream#destroy documentation.
  • Add test for broken subdoc subprop enum validation
  • add unmarkModified method
  • Trigger remove hooks on subdocs when removing parent
  • Add support for express-style error handling middleware
  • TypeError--
  • Make sure that createdAt does not get overriden
  • docs(api): fix link to populate() and add a new one from depopulate()
  • ownerDocument() now works when nesting arrays and single embedded doc…
  • fix(dependencies): upgrade mongodb version
  • Update subdocs.html
  • 4.6
  • should not cause unhandle reject promise when create fail
  • Babel (WIP)
  • Fix Indentation
  • Fixed issue #4592
  • reconnectFailed error from driver not being caught
  • #4629 Added test to reproduce
  • Object.keys fails when this.errors is null
  • Integration for ES6 classes
  • fixed two tests
  • fix: upgrade mongodb -> 2.2.12
  • fixed populate can not use more model
  • propagate strict option to a child schema
  • Update model.js
  • Adding return to promise callback to suppress bluebird promise warnings
  • feat(timestamps): support already defined timestamps
  • Add alias schema option
  • fix(model): return saved docs when create() fails
  • strictQuery option
  • feat(validation): include failed paths in error message and inspect output
  • Pass params to pre hooks
  • Make sharding into a plugin instead of core
  • When overwriting doc with update+overwrite, validate the whole doc
  • eachAsync `parallel` option
  • Activating Open Collective
  • Cache connection in useDb, replace connection.otherDbs array with a hashmap
  • docs(getting started): fix deprecation warning
  • support circular json
  • For https://github.com/Automattic/mongoose/issues/2596
  • For https://github.com/Automattic/mongoose/issues/2596
  • Doc save called twice it triggers TypeError: doc.toObject is not a function
  • (6223) adding null check before adding virtual to toJSON
  • Fix typo
  • Updating from vulnerable version of bson
  • Update promises.html
  • Add dbName parameter to documentation
mongoose questions on Stackoverflow (View All Questions)
  • Unable to install mongoose on windows 10
  • Cannot update mongoose attribute with .update()
  • Nodejs+Mongoose : find and update
  • Type Error in Promisifying Mongoose Connect
  • Mongoose - Does where cause a extra query?
  • Can't print property in array - Mongoose
  • find specific array from database using mongoose
  • Query to retrieve every subdocument alone without passing parent id using Mongoose
  • Mongoose Pre-Save Hook is Firing, but Not Saving Additional Field (NOT using model.update)
  • NodeJs, Mongoose: what's the best way to check auth before update?
  • Performance on sorting by populated field using mongoose
  • Get total count along with Mongoose Query skip & limt
  • MongoDB/Mongoose Update Embeded Array By Element Number
  • Connection to MongoDB via mongoose
  • Return single nested array object using mongoose
  • Cannot install mongoose using npm install
  • How to convert multiple Mongoose documents?
  • Virtual in Mongoose Object is Undefined?
  • What does require:true do in a Mongoose Schema? Below is an example
  • The XML you provided was not well-formed in mongoose
  • Best way to maintain only one schema between Mongoose and Joi
  • Select fields` values as array mongoose / mongodb aggregation
  • Mongoose QueryStream.pause() not pausing?
  • Trying to understand how mongoose populate or join works
  • FindOne in Mongoose Pre
  • How can I properly include csv data in my mongodb/mongoose/node.js app?
  • Mongoose Model Undefined in Pre Middleware
  • How can I make schema Given output using mongoose?
  • mongoose populate returns null array
  • NodeJS/Express File Upload to GridFS with Mongoose
mongoose list of languages used
Other projects in JavaScript