You are on page 1of 32

Lecture 9

Mongoose and mySql


 First keep in mind, Mongo DB is database
and mongoose is a module of node. You
have to install both
 Mongoose is an Object Document Mapper
(ODM).
 This means that Mongoose allows you to
define objects with a strongly-typed schema
that is mapped to a MongoDB document.

 Package to download
 npm install mongoose
 Better to do it with –g option to install it
globally
 First we are creating DB connection
 Connection to DB
 Creating Schema
 Making mongoose model
 Inserting data or error
 Searching and Updating
 Closing Db
 Basic connectivity
mongoose.connect('mongodb://localhost:27017/test’);
◦ For username/password
mongoose.connect('mongodb://username:password@host:port/databa
se’);
 First parameter is compulsory and it is DB connection as above.

 The connect function accepts two other optional parameters.


◦ The second parameter is an object of options where you can define things
like the username and password, if required.
◦ The third parameter, which can also be the second parameter if you have
no options, is the callback function after attempting to connect.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydb',
function (err) {
if (err) throw err;
console.log('Successfully connected');
});
If an error occurs when connecting to the
database, the exception is thrown and all
further processing is stopped. When no error
occurs, I have logged a success message to the
console.
 Everything in Mongoose starts with a Schema.
 Each schema maps to a MongoDB collection and defines the
shape of the documents within that collection.
 If you want to add additional keys later, use the Schema#add
method.
var Schema = mongoose.Schema;
var blogSchema = new Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});
 Schema & Schema Types
◦ It is key value pair where key is the property name and value is schema
type. It supports following types.
 String
 Number
 Date
 Buffer
 Mixed(Virtually anything but better to avoid using this type
 ObjectId( A reference to sub documents)
 Array
 Boolean
 Schema
◦ Each data type allows you to specify:
◦ a default value
◦ a custom validation function
◦ indicate a field is required
◦ a get function that allows you to manipulate the data before
it is returned as an object
◦ a set function that allows you to manipulate the data before
it is saved to the database
◦ create indexes to allow data to be fetched faster
var animalSchema = new Schema({
name: String,
type: String,
tags: { type: [String], index: true } // field level
});
animalSchema.index({ name: 1 }); // schema level
var child = new Schema({ name: String });
var schema = new Schema({ name: String, age: Number,
children: [child] });
var Tree = mongoose.model('Tree', schema);

// setting schema options


new Schema({ name: String }, { _id: false, autoIndex: false })
//_id=false will alow to eliminate _id field with each document
var userSchema = var authorSchema = mongoose.Schema({
mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId,
name: { name: {
firstName: String, firstName: String,
lastName: String
lastName: String },
}, biography: String,
created: Date twitter: String,
facebook: String,
}); linkedin: String,
profilePicture: Buffer,
created: {
type: Date,
default: Date.now
}
});
var mongoose = require('mongoose'); team: {
var Schema = mongoose.Schema; type: Schema.Types.ObjectId,
var TeamSchema = new Schema({ ref: 'Team'
name: {
},
image: {
type: String,
type: String,
required: true}
default: 'images/user.png'
});
},
var EmployeeSchema = new Schema({ address: {
name: { lines: {
first: { type: [String]
type: String, },
required: true}, postal: {
last: { type: String
type: String, }
required: true} }
}, });
 The team schema is defined to store only the name of the team.
 Every employee document is going to have a name object with a first and last
key. Both of those values are required and must be strings.
 The team key is how we can create a reference to another document/
schema. The Schema.Types.ObjectId indicates that the value for team is
going to be a MongoDB unique identifier and the ref key alerts Mongoose
what model to use when this value is populated from the database.
 The image key indicates that the value will be a string; if the value is absent,
images/user.png will be used instead.
 address consists of an array of strings for line and a string for postal.
 Looking at the completed schema, you’ll notice that it reads very easily. It is
quite clear at a glance how our documents are going to be structured in the
database.
 Remember, a schema tells Mongoose how data is going to be sent in and out
of our database. Suppose we want to add city to address in the future. With a
document storage database such as MongoDB, that would be a simple
change. We’d add city to Employee Schema, and now city would be available
to read and write for any Employee documents.
 Models are fancy constructors compiled from Schema
definitions. An instance of a model is called a document.
 Models are responsible for creating and reading documents
from the underlying MongoDB database.
 A Mongoose Model, when saved, creates a Document in
MongoDB with the properties as defined by the schema it is
derived from.
 we pass it into mongoose.model(modelName, schema)
var Author = mongoose.model('Author', authorSchema);
var Book = mongoose.model('Book', bookSchema);
 We are going to create several objects:
◦ an Author Model and several Book Models.
◦ Once created, these objects will be persisted to MongoDB using
the save method of the Model.
 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, the model Tank is for the tanks collection in
the database.
 The .model() function makes a copy of schema.
◦ Make sure that you've added everything you want to
schema before calling .model()!
◦ An instance of a model is called a document. Creating them
and saving to the database is easy.
var Tank = mongoose.model('Tank', yourSchema);
var small = new Tank({ size: 'small' });//instance of Model
small.save(function (err) {
if (err) return handleError(err);
// saved!
}); //OR
Tank.create({ size: 'small' }, function (err, small) {
if (err) return handleError(err);
// saved!
});
// or, for inserting large batches of documents
Tank.insertMany([{ size: 'small' }], function(err) {
});
mongoose.connect(dbUrl, function () {
console.log('connected!');
Team.create([{name: 'Product Development'}, {
name: 'Dev Ops'}, {name: 'Accounting'}],
function (error, pd, devops, acct) {
if (error) {console.log(error);
} else {console.dir(pd);
console.dir(devops);
console.dir(acct);
db.close();
process.exit();
}
});
});
 Mongoose use create command to insert the
documents one by one in loop internally.
 As we have a reference in employee schema
about team. So reference of object will be
saved.
 Keep in mind, this relationship will not
contain referential integrity etc
 New code is on next slide through methods.
var mvcBook = new Book {
_id: new mongoose.Types.ObjectId(),
title: 'ASP.NET MVC 5 with Bootstrap and
Knockout.js',
author: jamieAuthor._id,
ratings:[{
var jamieAuthor = new Author { summary: 'Great read'
_id: new mongoose.Types.ObjectId(), }]
name: { };

firstName: 'Jamie', mvcBook.save(function(err) {


lastName: 'Munro' if (err) throw err;
}, console.log('Book successfully saved.');
biography: 'Jamie is the author of });
ASP.NET MVC 5 with Bootstrap and
Knockout.js.', var knockoutBook = new Book {
_id: new mongoose.Types.ObjectId(),
twitter: title: 'Knockout.js: Building Dynamic Client-
'https://twitter.com/endyourif', Side Web Applications',
facebook: author: jamieAuthor._id
'https://www.facebook.com/End-Your- };
If-194251957252562/'
knockoutBook.save(function(err) {
}; if (err) throw err;
jamieAuthor.save(function(err) {
console.log('Book successfully saved.');
if (err) throw err; });
console.log('Author successfully });
saved.');
mongoose.connect(dbUrl, function (err) {
Var mongoose=require(‘mongoose’);
if (err) {
var db = mongoose.connection; return console.log('there was a problem
var dbUrl = connecting to the database!' + err);
'mongodb://localhost:27017
}
/humanresources'; console.log('connected!');
var TeamSchema = new var team = new Team({
mongoose.schema({ name: 'Product Development'
name: { });
type: String, team.save(function (error, data) {
required: true if (error) {
} console.log(error);
}); } else {
var Team = mongoose.model('Team', console.dir(data);
TeamSchema); }
db.close();
process.exit();
});
});
 Mongoose provides several different functions to
find data for a specific Model.
 The functions are find, findOne, and findById.
◦ The find and findOne functions both accept an object as
input allowing for complex searches
◦ findById accepts just a single value with a callback function.
◦ Find will return all while findOne will return first match
Team.find({
name: /dev/i}).exec(function(err, books) {
if (err) throw err;
console.log(books);
});
Here mvc is case insensitive.
 The find function call also be chained to other
query methods, such as where, and, or, limit,
sort, any, etc.
Book.find({
title: /mvc/i
}).sort('created')
.limit(5)
.exec(function(err, books) {
if (err) throw err;

console.log(books);
});
 findById is executed immediately and accepts
a callback function, instead of allowing for a
chain of functions.
Author.findById('59b31406beefa1082819e72f', function(err, author) {
if (err) throw err;
console.log(author);
});
 Once an object has been returned, you can modify any of its
properties to update it.
 Once you have made the necessary changes, you call the save
method, just like when you were creating the object.
Model.findOneAndUpdate({ name: 'borne' }, { name: 'jason bourne’
},callback)
Author.findById('59b31406beefa1082819e72f', function(err, author) {
if (err) throw err;
author.linkedin = 'https://www.linkedin.com/in/jamie-munro-
8064ba1a/';
author.save(function(err) {
if (err) throw err
console.log('Author updated successfully');
});
});
 After the author is successfully retrieved, the linkedin property is set
and the save function is called.
 Mongoose is able to detect that the linkedin property was changed,
and it will send an update statement to MongoDB on only the
properties that have been modified.
 Mongoose also offers two additional functions that
make finding an object and saving it in a single
step.
 findByIdAndUpdate and findOneAndUpdate
Author.findByIdAndUpdate('59b31406beefa1082819e72f',
{ linkedin: 'https://www.linkedin.com/in/jamie-munro-8064ba1a/'
},
function(err, author) {
if (err) throw err;
console.log(author);
});
 Deleting
Models have static deleteOne() and deleteMany() functions for
removing all documents matching the given filter.

Tank.deleteOne({ size: 'large' }, function (err) {


if (err) return handleError(err);
// deleted at most one tank document
});
 Simply connection object.close()
 For example
◦ Db.close();
var mongoose = require('mongoose');
//require database URL from properties file
var dbURL = require('./property').db;
//export this function and imported by server.js
module.exports =function(){
mongoose.connect(dbURL);
mongoose.connection.on('connected', function(){
console.log(connected("Mongoose default connection is open to ", dbURL));
});
mongoose.connection.on('error', function(err){
console.log(error("Mongoose default connection has occured "+err+" error"));
});
mongoose.connection.on('disconnected', function(){
console.log(disconnected("Mongoose default connection is disconnected"));
});
process.on('SIGINT', function(){
mongoose.connection.close(function(){
console.log(termination("Mongoose default connection is disconnected due to application
termination"));
process.exit(0)
}); });
}
 NoSQL
◦ alternatives such as Redis1, CouchDB2, and
Cassandra3.
 SQL Based
◦ MySQL, Oracle , or SQL Server
4 5

 BUT
 It is not in meanstack
var mysql = require('mysql');
var connection =
mysql.createConnection('mysql://user:secret@localhost:3306/dbname');
connection.connect(function(error) {
if (error) {
return console.error(error.message);}
console.log('successfully connected!');});
var insertSql = 'INSERT INTO Presidents (Name, Terms) VALUES' +
'(\'Bill Clinton\', 2),’ + '(\'George W Bush\', 2)';
connection.query(insertSql, function(error, results) {
if (error) {
connection.release();
return console.error(error.message);
}
var selectSql = 'SELECT * FROM Presidents';
connection.query(selectSql, function(error,
results) {
if (error) {
connection.release();
return console.error(error.message);
}
console.log('results of SELECT:');
console.log(JSON.stringify(results, null, 2));

You might also like