Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks.
The official documentation website is 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 our docs site.
Pull requests are always welcome! Please base pull requests against the
branch and follow the contributing guide.
If your pull requests makes documentation changes, please do not
.html files. The
.html files are compiled code, so please make
your changes in
View all 400+ contributors.
$ npm install mongoose
// Using Node.js `require()`const mongoose = ;// Using ES6 imports;
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.
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
createConnection take a
mongodb:// URI, or the parameters
host, database, port, options.
Once connected, the
open event is fired on the
Connection instance. If you're using
mongoose.createConnection return value is a
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
const Schema = mongooseSchema;const ObjectId = SchemaObjectId;const BlogPost =author: ObjectIdtitle: Stringbody: Stringdate: Date;
Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of:
- Validators (async and sync)
- Methods definition
- Statics definition
The following example shows some of these features:
const Comment =name: type: String default: 'hahaha'age: type: Number min: 18 index: truebio: type: String match: /[a-z]/date: type: Date default: Datenowbuff: Buffer;// a setterComment;// middlewareComment;
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;
Or just do it all at once
const MyModel = mongoose;
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;
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 = ;instancemykey = 'hello';instance;
Or we can find documents from the same collection
You can also
const instance = await MyModel;console; // '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;const MyModel = conn;const m = ;m; // works
const conn = mongoose;const MyModel = mongoose;const m = ;m; // does not work b/c the default connection object was never connected
In the first example snippet, we defined a key in the Schema that looks like:
Comment is a
Schema we created. This means that creating embedded documents is as simple as:
// retrieve my modelconst BlogPost = mongoose;// create a blog postconst post = ;// create a commentpostcomments;post;
The same goes for removing them:
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!
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:
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
;// pre declaration is chainable;
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:
broken: type: Booleanasset:name: Stringtype: String // uh oh, it broke. asset will be interpreted as String;works: type: Booleanasset:name: Stringtype: type: String // works. asset is an object with a type property;
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.
Express Session Stores
Copyright (c) 2010 LearnBoost <email@example.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.