mongoose

Getting started with mongoose

Remarks#

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

Versions#

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

VersionRelease Date
1.0.12011-02-02
1.1.62011-03-22
1.3.02011-04-19
1.3.12011-04-27
1.3.42011-05-17
1.4.02011-06-10
1.5.02011-06-27
1.6.02011-07-07
2.0.02011-08-24
2.3.42011-10-18
2.5.02012-01-26
3.0.02012-08-07
3.1.22012-09-10
3.2.02012-09-27
3.5.02012-12-10
3.5.62013-02-14
3.6.02013-03-18
3.6.52013-04-15
3.8.02013-10-31
3.8.102014-05-20
3.8.152014-08-17
4.0.02015-03-25
4.0.62015-06-21
4.1.02015-07-24
4.2.02015-10-22
4.2.102015-12-08
4.3.52016-01-09
4.4.02016-02-02
4.4.42016-02-17
4.4.82016-03-18
4.4.132016-04-21
4.4.182016-05-21
4.5.02016-06-13
4.5.52016-07-18
4.5.82016-08-01
4.5.92016-08-14
4.5.102016-08-23
4.6.02016-09-02

Installation

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.


Connecting to 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.

Connection with options and callback

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
});

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow