MongoDB and Mongoose
Object-document Model
Telerik Software Academy
Learning & Development
[Link]
Table of Contents
MongoDB Native Overview
Mongoose Overview
Mongoose Models
Types of properties
Virtual methods
Property validation
Mongoose CRUD operations
Save, remove, find
Mongoose Queries
MongoDB Native Overview
Using MongoDB
Download MongoDB from the official web site:
[Link]
Installers for all major platforms
When installed,MongoDB needs a driver to be
usable with a specific platform
One to use with [Link], another to use with
.NET, etc
Installing MongoDB driver for [Link]:
$ npm install mongodb -g
Working with MongoDB
from [Link]
Once installed, the MongoDB must be started
Go to installation folder and run mongod
$ cd path/to/mondodb/installation/folder
$ mondgod
Or add [Link] to the PATH
When run, the MongoDB can be used from
[Link]
Creating MongoDB Database
The database is created using [Link]
The 'mongodb' module is required
var mongodb = require('mongodb');
Create a server to host the database
var server = new [Link]('localhost', 27017);
Create mongodb client that connects to the server
var mongoClient = new [Link](server);
Open connection to the mongodb server
[Link](function(err, client){
var db = [Link]('DATABASE_NAME');
//queries over the db
});
Queries over MongoDB
with [Link]
MongoDB module supports all kinds of queries
over the data
Creating new documents
And adding records
Editing existing documents
And their records
Removing documents and records
Querying whole documents or parts of them
[Link] and MongoDB
Live Demo
Mongoose Overview
Mongoose Overview
Mongoose is a object-document model module
in [Link] for MongoDB
Wraps the functionality of the native MongoDB
driver
Exposes models to control the records in a doc
Supports validation on save
Extends the native queries
Installing Mongoose
Run the following from the CMD/Terminal
$ npm install mongoose
In node
Load the module
var mongoose = require('mongoose');
Connect to the database
[Link](mongoDbPath);
Create models and persist data
var Unit = [Link]('Unit', { type: String} );
new Unit({type: 'warrior'}).save(callback); //create
[Link]({type: 'warrior'}).exec(callback); //fetch
Installing and Using
Mongoose
Live Demo
Mongoose Models
Mongoose Models
Mongoose supports models
i.e. fixed types of documents
Used like object constructors
Needs a [Link]
var modelSchema = new [Link]({
propString: String,
propNumber: Number,
propObject: {},
propArray: [],
propBool: Boolean
});
var Model = [Link]('Model', modelSchema);
Mongoose Models (2)
Each of the properties must have a type
Types can be Number, String, Boolean, array,
object
Even nested objects
var modelSchema = new [Link]({
propNested: {
propNestedNumber: Number,
propDoubleNested: {
propArr: []
}
});
var Model = [Link]('Model', modelSchema);
Mongoose Models
Live Demo
Mongoose Models with
Instance Methods
Since mongoose models are just JavaScript object
constructors they can have methods
And these methods can be added to a schema
Use a different syntax than plain JS
var unitSchema = new [Link]({});
[Link] = function(to){
};
And now can be called on a model of type Unit
var unit = new Unit({ } );
[Link]({x: 5, y: 6});
Mongoose Models with
Instance Methods
Live Demo
Mongoose Models with
Virtual Properties
Yet, not all properties need to be persisted to
the database
Mongoose provides a way to create properties,
that are accessible on all models, but are not
persisted to the database
And they have both getters and setters
var unitSchema = new [Link]({});
[Link]('escapedTitle').get(function(){ });
[Link]('escapedTitle').set(function(title){ });
Virtual Properties
Live Demo
Property Validation
Property Validation
With Mongoose developers can define custom
validation on their properties
i.e. validate records when trying to save
var unitSchema = new [Link]({});
[Link]('position.x').validate(function(value){
return value>=0 && value <= maxX;
});
[Link]('position.y').validate(function(value){
return value>=0 && value <= maxY;
});
Property Validation
Live Demo
CRUD with Mongoose
CRUD with Mongoose
Mongoose supports all the CRUD operations:
Create > [Link](callback)
Read > [Link]().exec(callback)
Update > [Link](props, callback)
> [Link](condition, props, cb)
Remove > [Link](callback)
> [Link](condition, props, cb)
CRUD Operations with
Mongoose
Live Demo
Mongoose Queries
Mongoose Queries
Mongoose defines all
queries of the native
MongoDB driver in a more clear and useful way
Instead of:
{$or: [{conditionOne: true},
{conditionTwo: true}]
}
Do:
.where({conditionOne: true}).or({conditionTwo: true})
Mongoose Queries (2)
Mongoose supports many queries:
For equality/non-equality
Selection of some properties
Sorting
Limit & skip
All
queries are executed over the object
returned by [Link]*()
Call .exec() at the end to run the query
Mongoose Queries
Live Demo
Mongoose Models Modules
Mongoose Models
Having all model definitions in the main
module is no good
That is the reason [Link] has modules in the
first place
We can put each model in a different module,
and load all models at start
Mongoose Models Modules
Live Demo
MongoDB and Mongoose
, BG Coder - - online judge
,
[Link] - , , C#, .NET, [Link]
[Link]
[Link] MVC HTML, SQL, C#, .NET, [Link] MVC
SEO - ,
, iPhone, Android, WP7, PhoneGap
, HTML, CSS, JavaScript, Photoshop -
free C# book, C#, Java, C# -
" "
" cloud " C# , ,
Homework
1. Create a modules for Chat, that keep the data into a
local MongoDB instance
The module should have the following functionality:
var chatDb = require('chat-db');
//inserts a new user records into the DB
[Link]({user: 'DonchoMinkov', pass: '123456q'});
//inserts a new message record into the DB
//the message has two references to users (from and to)
[Link]({
from: 'DonchoMinkov',
to: 'NikolayKostov',
text: 'Hey, Niki!'
});
//returns an array with all messages between two users
[Link]({
with: 'DonchoMinkov',
and: 'NikolayKostov
});