Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment.
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
Mongoose makes it painlessly easy to work with MongoDB database.
We can easily structure our database using Schemas and Models
, Automate certain things when record is added or updated using Middlewares/Hooks
and easily get the data we need by querying
our models.
Important Links
Latest release: Version 4.6.0 released on 2nd September 2016
All versions can be found at https://github.com/Automattic/mongoose/blob/master/History.md
Version | Release Date |
---|---|
1.0.1 | 2011-02-02 |
1.1.6 | 2011-03-22 |
1.3.0 | 2011-04-19 |
1.3.1 | 2011-04-27 |
1.3.4 | 2011-05-17 |
1.4.0 | 2011-06-10 |
1.5.0 | 2011-06-27 |
1.6.0 | 2011-07-07 |
2.0.0 | 2011-08-24 |
2.3.4 | 2011-10-18 |
2.5.0 | 2012-01-26 |
3.0.0 | 2012-08-07 |
3.1.2 | 2012-09-10 |
3.2.0 | 2012-09-27 |
3.5.0 | 2012-12-10 |
3.5.6 | 2013-02-14 |
3.6.0 | 2013-03-18 |
3.6.5 | 2013-04-15 |
3.8.0 | 2013-10-31 |
3.8.10 | 2014-05-20 |
3.8.15 | 2014-08-17 |
4.0.0 | 2015-03-25 |
4.0.6 | 2015-06-21 |
4.1.0 | 2015-07-24 |
4.2.0 | 2015-10-22 |
4.2.10 | 2015-12-08 |
4.3.5 | 2016-01-09 |
4.4.0 | 2016-02-02 |
4.4.4 | 2016-02-17 |
4.4.8 | 2016-03-18 |
4.4.13 | 2016-04-21 |
4.4.18 | 2016-05-21 |
4.5.0 | 2016-06-13 |
4.5.5 | 2016-07-18 |
4.5.8 | 2016-08-01 |
4.5.9 | 2016-08-14 |
4.5.10 | 2016-08-23 |
4.6.0 | 2016-09-02 |
Mongoose connect has 3 parameters, uri, options, and the callback function. To use them see sample below.
var mongoose = require('mongoose');
var uri = 'mongodb://localhost:27017/DBNAME';
var options = {
user: 'user1',
pass: 'pass'
}
mongoose.connect(uri, options, function(err){
if (err) throw err;
// if no error == connected
});
Installing mongoose is as easy as running the npm
command
npm install mongoose --save
But make sure you have also installed MongoDB
for your OS or Have access to a MongoDB database.
1. Import mongoose into the app:
import mongoose from 'mongoose';
2. Specify a Promise library:
mongoose.Promise = global.Promise;
3. Connect to MongoDB:
mongoose.connect('mongodb://127.0.0.1:27017/database');
/* Mongoose connection format looks something like this */
mongoose.connect('mongodb://USERNAME:PASSWORD@HOST::PORT/DATABASE_NAME');
Note:
By default mongoose connects to MongoDB at port 27017
, Which is the default port used by MongoDB.
To connect to MongoDB hosted somewhere else, use the second syntax. Enter MongoDB username, password, host, port and database name.
MongoDB port is 27017 by default; use your app name as the db name.