87
node.js databases Thomas Dunajski gfnork webentwicklungsunternehmen Redis, NoSQL, MongoDB, drivers

node.js workshop- node.js databases

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: node.js workshop- node.js databases

node.js databases

Thomas Dunajskigfnork webentwicklungsunternehmen

Redis, NoSQL, MongoDB, drivers

Page 2: node.js workshop- node.js databases

2

Redis

Page 3: node.js workshop- node.js databases

3

What is Redis?NoSQL key-value data store"memcached with built-in persistence" open source

Page 4: node.js workshop- node.js databases

4

Why should I use Redis?fast (saves data in RAM if possible)keeps a copy on Disc scales goodrarely used values are swapped out to disk if RAM is lowcan save complex javascript objectseasy to usegreat for Apps with small reqirements

Page 5: node.js workshop- node.js databases

5

What is SQL/NoSQL? (very simplified)SQL databases store data in tables all data needs to match the format of the tabletend to be more stabelare scaled by using better hardware(vertical scaling)NoSQL does not use tablesitems in the database do not need to have the same formatare scaled by using more hardware(horizontal scaling)depending on what you want to do one will be better than the other

Page 6: node.js workshop- node.js databases

6

NoSQL database typesKey-value storesitems are keys(names) with one valueDocument databases each key has a complex data structure instead of a valueGraph storesstore information about networks (i.e . social connection)Wide-column storesstore columns of data together instead of rows

Page 7: node.js workshop- node.js databases

7

How to get Redis running?download it on http://redis.io/downloadcompile itrun src/redis-servernpm install redis

Page 8: node.js workshop- node.js databases

8

How to use Redis?var redis = require("redis") , client = redis.createClient();

client.set("key", "Your Data", function (err, reply) { //do something }); client.get("key", function (err, reply) { console.log(reply.toString()); });=> Your Data

Page 9: node.js workshop- node.js databases

9

How to use Redis?var redis = require("redis") , client = redis.createClient();

client.set("key", "Your Data", function (err, reply) { //do something }); client.get("key", function (err, reply) { console.log(reply.toString()); });=> Your Data

Page 10: node.js workshop- node.js databases

10

How to use Redis?var redis = require("redis") , client = redis.createClient();

Import the redis driver

make an Instance of

a connection

Page 11: node.js workshop- node.js databases

11

How to use Redis?var redis = require("redis") , client = redis.createClient();

client.set("key", "Your Data", function (err, reply) { //do something }); client.get("key", function (err, reply) { console.log(reply.toString()); });=> Your Data

Page 12: node.js workshop- node.js databases

12

How to use Redis?

client.set("key", "Your Data", function (err, reply) { //do something });

Insert Command Value CallbackKey

Page 13: node.js workshop- node.js databases

13

How to use Redis?var redis = require("redis") , client = redis.createClient();

client.set("key", "Your Data", function (err, reply) { //do something }); client.get("key", function (err, reply) { console.log(reply.toString()); });=> Your Data

Page 14: node.js workshop- node.js databases

14

How to use Redis?

client.get("key", function (err, reply) { console.log(reply.toString()); });

Load Command Key Callback

Page 15: node.js workshop- node.js databases

15

Questions?var redis = require("redis") , client = redis.createClient();

client.set("key", "Your Data", function (err, reply) { //do something }); client.get("key", function (err, reply) { console.log(reply.toString()); });=> Your Data

Page 16: node.js workshop- node.js databases

16

MongoDB

Page 17: node.js workshop- node.js databases

17

What is MongoDBNoSQL document-orientated-database cross platform open source

Page 18: node.js workshop- node.js databases

18

Document databasesdocument databases pair keys with complex data structuresthis complex data structures are called documentsdocuments can contain key-value pairskey-array pairsnested documents

Page 19: node.js workshop- node.js databases

19

Why should i use MongoDBfast (saves data in RAM if possible)scales great(sharding)failure resistent(replica sets)easy to usehigh development speedunderstands JSONsuports geo-querys

Page 20: node.js workshop- node.js databases

20

What is a Replica Set?multiple machines have the same dataif one crashes the data is still accessiblesuch a group of machines is called Replica Set

Page 21: node.js workshop- node.js databases

21

Replica Sets

Node 1

Primary

Node 1

Secondary

Node 1

Secondary

Page 22: node.js workshop- node.js databases

22

Replica Sets

Node 1

Node 1

Secondary

Node 1

SecondaryElection

Page 23: node.js workshop- node.js databases

23

Replica Sets

Node 1

Node 1Node 1

Secondary Primary

Page 24: node.js workshop- node.js databases

24

Replica Sets

Node 1

Node 1

Secondary

Node 1

Secondary Primary

Page 25: node.js workshop- node.js databases

25

What is Shardingspliting data on multiple machinesdata packages are called chunkscunks that exeed 64MB are split in twosingle machines are called shardsthe shard key is the value that decides to witch chunk a entry belongsWARNING: the shard key can only be set once

Page 26: node.js workshop- node.js databases

26

Sharding

a

c

d

Shard1

b e

Shard2

Page 27: node.js workshop- node.js databases

27

Sharding

a

c1

d

Shard1

b e

Shard2

c2

Page 28: node.js workshop- node.js databases

28

Sharding

a

c1

d

Shard1

b e

Shard2

c2

Page 29: node.js workshop- node.js databases

29

Real Deployment

mongod

mongod

mongod

Replica Set

mongod

mongod

mongod

Replica Set

mongod

mongod

mongod

Replica Set

mongod

mongod

mongod

Config Servers

mongos

Client

Page 30: node.js workshop- node.js databases

30

How to get MongoDB running(Ubuntu)?sudo apt-get install mongodb sudo service mongodb start

Page 31: node.js workshop- node.js databases

31

How to get MongoDB running(Windows)?go to http://www.mongodb.org/downloadsdownload the setup install itrun mongod.exe

Page 32: node.js workshop- node.js databases

32

What is ORM?Object-Relational Mapper is a piece of software that transforms objects to relations that can be saved in a database and vice versa

Page 33: node.js workshop- node.js databases

33

What Driver should you use?depends on your needs...Mongoose – Object Relational Mapper MongoskinNode MongoDB Native Driver

Page 34: node.js workshop- node.js databases

34

MongooseProsschema-basedbuilt-in type castingbuild-in validation and other usefull features

Consslow

Page 35: node.js workshop- node.js databases

35

MongoskinProsfastlightweight

Conslightweight

Page 36: node.js workshop- node.js databases

36

Node MongoDB Native DriverProsfastest DriverConsLeast comfortable

I only use Node MongoDB Native Driver when I need maximum performance Mongoskin is fast enough for almost anything

Page 37: node.js workshop- node.js databases

37

How to use Mongoskin?//npm install mongoskin var db = require('mongoskin').db( 'localhost:27017/Workshop');

db.collection('participants').insert({name: "Noob", skills: []}, function(err, result) { if (err) throw err; if (result) console.log('Added!');});=>Added!

db.collection('participants').insert({name: "Geek", skills: ['Node.js' , 'MongoDB']}, function(err, result) { if (err) throw err; if (result) console.log('Added!');});=> Added!

Page 38: node.js workshop- node.js databases

38

How to use Mongoskin?//npm install mongoskin var db = require('mongoskin').db( 'localhost:27017/Workshop');

db.collection('participants').insert({name: "Noob", skills: []}, function(err, result) { if (err) throw err; if (result) console.log('Added!');});=>Added!

db.collection('participants').insert({name: "Geek", skills: ['Node.js' , 'MongoDB']}, function(err, result) { if (err) throw err; if (result) console.log('Added!');});=> Added!

Page 39: node.js workshop- node.js databases

39

How to use Mongoskin?

var db = require('mongoskin').db('localhost:27017/Workshop');

assigning Connection to

dbimport Connectiong

to db

Host Adress Port

Database Name

Page 40: node.js workshop- node.js databases

40

How to use Mongoskin?//npm install mongoskin var db = require('mongoskin').db( 'localhost:27017/Workshop');

db.collection('participants').insert({name: "Noob", skills: []}, function(err, result) { if (err) throw err; if (result) console.log('Added!');});=>Added!

db.collection('participants').insert({name: "Geek", skills: ['Node.js' , 'MongoDB']}, function(err, result) { if (err) throw err; if (result) console.log('Added!');});=> Added!

Page 41: node.js workshop- node.js databases

41

How to use Mongoskin?

db.collection('participants').insert({name: "Noob", skills: []}, function(err, result) { if (err) throw err; if (result) console.log('Added!');});

Get a Collection

Collection Name

Insert Command

A Java Script Object

Callback

Page 42: node.js workshop- node.js databases

42

Questions?//npm install mongoskin var db = require('mongoskin').db( 'localhost:27017/Workshop');

db.collection('participants').insert({name: "Noob", skills: []}, function(err, result) { if (err) throw err; if (result) console.log('Added!');});=>Added!

db.collection('participants').insert({name: "Geek", skills: ['Node.js' , 'MongoDB']}, function(err, result) { if (err) throw err; if (result) console.log('Added!');});=> Added!

Page 43: node.js workshop- node.js databases

43

How to use Mongoskin?

db.collection('participants').find().toArray(function(err, result) { if (err) throw err; console.log(result); }); =>[ { _id: 5375ea17898372a81425297a, name: 'Noob', skills: [] }, { _id: 5375ea17898372a81425297b, name: 'Geek', skills: [ 'Node.js', 'MongoDB' ] } ]

Page 44: node.js workshop- node.js databases

44

How to use Mongoskin?

db.collection('participants').find().toArray(function(err, result) { if (err) throw err; console.log(result); }); =>[ { _id: 5375ea17898372a81425297a, name: 'Noob', skills: [] }, { _id: 5375ea17898372a81425297b, name: 'Geek', skills: [ 'Node.js', 'MongoDB' ] } ]

Page 45: node.js workshop- node.js databases

45

How to use Mongoskin?

db.collection('participants').find().toArray(function(err, result) { if (err) throw err; console.log(result); });

Returns a Collection

Search Command

Converts a Cursor to an

Array

Page 46: node.js workshop- node.js databases

46

How to use Mongoskin?

db.collection('participants').findOne({name:'Geek'}, function(err, result) { console.log('Geeks skills:'); console.log(result.skills);});=>Geeks skills: [ 'Node.js', 'MongoDB' ]

Returns a single Object

can be used like any other

Object

Page 47: node.js workshop- node.js databases

47

How to use Mongoose?var mongoose = require('mongoose').db( 'localhost:27017/Workshop'), db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));db.once('open', function callback () { console.log('Connected!')});

var participantSchema = mongoose.Schema({ name: String, skills:[String]});var Participant = mongoose.model('Participant', participantSchema);

Page 48: node.js workshop- node.js databases

48

How to use Mongoose?var mongoose = require('mongoose').db( 'localhost:27017/Workshop'), db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));db.once('open', function callback () { console.log('Connected!')});

var participantSchema = mongoose.Schema({ name: String, skills:[String]});var Participant = mongoose.model('Participant', participantSchema);

Page 49: node.js workshop- node.js databases

49

How to use Mongoose?

var mongoose = require('mongoose').db( localhost:27017/Workshop'),

import Connectiong to db

Host Adress Port

Database Name

assigning Connection to Variable db

Page 50: node.js workshop- node.js databases

50

How to use Mongoose?var mongoose = require('mongoose').db( 'localhost:27017/Workshop'), db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));db.once('open', function callback () { console.log('Connected!')});

var participantSchema = mongoose.Schema({ name: String, skills:[String]});var Participant = mongoose.model('Participant', participantSchema);

assigning Connection to Variable db

Page 51: node.js workshop- node.js databases

51

How to use Mongoose?var mongoose = require('mongoose').db( 'localhost:27017/Workshop'), db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));db.once('open', function callback () { console.log('Connected!')});

var participantSchema = mongoose.Schema({ name: String, skills:[String]});var Participant = mongoose.model('Participant', participantSchema);

Page 52: node.js workshop- node.js databases

52

How to use Mongoose?

db.on('error', console.error.bind(console, 'connection error:'));

Reactiong to Event Event Name Handling

ErrorWhere the

Ountput gets piped to

String attached to

Error Message

Page 53: node.js workshop- node.js databases

53

How to use Mongoose?var mongoose = require('mongoose').db( 'localhost:27017/Workshop'), db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));db.once('open', function callback () { console.log('Connected!')});

var participantSchema = mongoose.Schema({ name: String, skills:[String]});var Participant = mongoose.model('Participant', participantSchema);

Page 54: node.js workshop- node.js databases

54

How to use Mongoose?

db.once('open', function callback () { console.log('Connected!')});

Event that will only be done once

Event Name

Page 55: node.js workshop- node.js databases

55

How to use Mongoose?var mongoose = require('mongoose').db( 'localhost:27017/Workshop'), db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));db.once('open', function callback () { console.log('Connected!')});

var participantSchema = mongoose.Schema({ name: String, skills:[String]});var Participant = mongoose.model('Participant', participantSchema);

Page 56: node.js workshop- node.js databases

56

How to use Mongoose?

var participantSchema = mongoose.Schema({ name: String, skills:[String]});

Schema Name

Mongoose Object

Function for defining Schemas

Variables

Page 57: node.js workshop- node.js databases

57

How to use Mongoose?var mongoose = require('mongoose').db( 'localhost:27017/Workshop'), db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));db.once('open', function callback () { console.log('Connected!')});

var participantSchema = mongoose.Schema({ name: String, skills:[String]});var Participant = mongoose.model('Participant', participantSchema);

Page 58: node.js workshop- node.js databases

58

How to use Mongoose?

var Participant = mongoose.model('Participant', participantSchema);

Model NameFunction for

creating Models

Model Name Schema Name

Page 59: node.js workshop- node.js databases

59

Questions?var mongoose = require('mongoose').db( 'localhost:27017/Workshop'), db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));db.once('open', function callback () { console.log('Connected!')});

var participantSchema = mongoose.Schema({ name: String, skills:[String]});var Participant = mongoose.model('Participant', participantSchema);

Page 60: node.js workshop- node.js databases

60

How to use Mongoose?var noob= new Participant({ name: 'Noob', skills:[]});noob.save(function( err, result) { if( err) return console.error(err); if (result) console.log('Added!');});=> Added!var geek= new Participant({ name: 'Geek', skills:['Node.js' , 'MongoDB']});geek.save(function (err, result) { if (err) return console.error(err); if (result) console.log('Added!');});=> Added!

Page 61: node.js workshop- node.js databases

61

How to use Mongoose?var noob= new Participant({ name: 'Noob', skills:[]});noob.save(function( err, result) { if( err) return console.error(err); if (result) console.log('Added!');});=> Added!var geek= new Participant({ name: 'Geek', skills:['Node.js' , 'MongoDB']});geek.save(function (err, result) { if (err) return console.error(err); if (result) console.log('Added!');});=> Added!

Page 62: node.js workshop- node.js databases

62

How to use Mongoose?

var noob= new Participant({ name: 'Noob', skills:[]});

Creating new Instance of

Model

JS Object matching Schema

Page 63: node.js workshop- node.js databases

63

How to use Mongoose?var noob= new Participant({ name: 'Noob', skills:[]});noob.save(function( err, result) { if( err) return console.error(err); if (result) console.log('Added!');});=> Added!var geek= new Participant({ name: 'Geek', skills:['Node.js' , 'MongoDB']});geek.save(function (err, result) { if (err) return console.error(err); if (result) console.log('Added!');});=> Added!

Page 64: node.js workshop- node.js databases

64

How to use Mongoose?

noob.save(function( err, result) { if( err) return console.error(err); if (result) console.log('Added!');});

Function for saving

Page 65: node.js workshop- node.js databases

65

Questions?var noob= new Participant({ name: 'Noob', skills:[]});noob.save(function( err, result) { if( err) return console.error(err); if (result) console.log('Added!');});=> Added!var geek= new Participant({ name: 'Geek', skills:['Node.js' , 'MongoDB']});geek.save(function (err, result) { if (err) return console.error(err); if (result) console.log('Added!');});=> Added!

Page 66: node.js workshop- node.js databases

66

How to use Mongoose?Participant.find(function (err, result) { if (err) return console.error(err); console.log(result)});=> [ { _id: 5375fb170ccdac981527120e, name: 'Noob', __v: 0, skills: [] }, { _id: 5375fb170ccdac981527120f, name: 'Geek', __v: 0, skills: [ 'Node.js', 'MongoDB' ] } ]

Page 67: node.js workshop- node.js databases

67

How to use Mongoose?Participant.find(function (err, result) { if (err) return console.error(err); console.log(result)});=> [ { _id: 5375fb170ccdac981527120e, name: 'Noob', __v: 0, skills: [] }, { _id: 5375fb170ccdac981527120f, name: 'Geek', __v: 0, skills: [ 'Node.js', 'MongoDB' ] } ]

Page 68: node.js workshop- node.js databases

68

How to use Mongoose?

Participant.find(function (err, result) { if (err) return console.error(err); console.log(result)});

Returns An Array of Objects

Page 69: node.js workshop- node.js databases

69

How to use Mongoose?Participant.findOne({ name: 'Geek' }, function (err, result) { if (err) return console.error(err); console.log('Geeks skills:'); console.log(result.skills);});

=> Geeks skills: [ Node.js, MongoDB]

Page 70: node.js workshop- node.js databases

70

How to use Mongoose?Participant.find({ name: 'Geek' }, 'skills',function (err, result) { if (err) return console.error(err); console.log('Geeks skills:'); console.log(result); });=> Geeks skills: [ { _id: 5375f79aaa515144156ee3eb, skills: [ 'Node.js', 'MongoDB' ] } ]

Page 71: node.js workshop- node.js databases

71

How to use Mongoose?Participant.find({ name: 'Geek' }, 'skills',function (err, result) { if (err) return console.error(err); console.log('Geeks skills:'); console.log(result); });=> Geeks skills: [ { _id: 5375f79aaa515144156ee3eb, skills: [ 'Node.js', 'MongoDB' ] } ]

Page 72: node.js workshop- node.js databases

72

How to use Mongoose?

Participant.find({ name: 'Geek' }, 'skills',function (err, result) {

Key

Searches Objects with the Name 'Geek' and returns the Value for the Key

'skills'

Page 73: node.js workshop- node.js databases

73

How to use Mongoose?Participant.find({ name: 'Geek' }, 'skills',function (err, result) { if (err) return console.error(err); console.log('Geeks skills:'); console.log(result); });=> Geeks skills: [ { _id: 5375f79aaa515144156ee3eb, skills: [ 'Node.js', 'MongoDB' ] } ]

Page 74: node.js workshop- node.js databases

74

What are indexes and why do i need them?indexes are similar to a table of contents in a bookit keeps you from having to read the whole book to get an answer on a questioninstead you can find the right page by checkin the indexmore technically said you speed up the query by allowing it to search a smaller subset of data

Page 75: node.js workshop- node.js databases

75

MongolabDemotime!

Page 76: node.js workshop- node.js databases

76

How to make Indexes?db.collection("participants").ensureIndex( {name: 1 }, function(err) { if (err) throw err; else console.log('done writing indexes'); });

db.participants.ensureIndex( {name: 1 })

Page 77: node.js workshop- node.js databases

77

How to make Indexes?

db.collection("participants").ensureIndex( {name: 1 }, function(err) { if (err) throw err; else console.log('done writing indexes'); });

db.participants.ensureIndex( {name: 1 })

Get a Collection

Command for making Indexes

Name of the Key that has to be indexed

1 = Ascending

2 = Descending

Page 78: node.js workshop- node.js databases

78

Questions?

Page 79: node.js workshop- node.js databases

79

Exercise Datadb.collection('querys').insert({name: "a", number: 1}) db.collection('querys').insert({name: "a", number: 2}) db.collection('querys').insert({name: "a", number: 3}) db.collection('querys').insert({name: "b", number: 1}) db.collection('querys').insert({name: "b", number: 2})db.collection('querys').insert({name: "b", number: 3})db.collection('querys').insert({name: "c", number: 1})db.collection('querys').insert({name: "c", number: 2})db.collection('querys').insert({name: "c", number: 3, bool: false})

Page 80: node.js workshop- node.js databases

80

ExerciseWrite a Node.js application that connects to : mongodb://usr:[email protected]:45089/workshopwrite functions that return items matching the following conditions1. name=a2. name=a, number=33. name=a or number=34. number is smaller than 25. all items that have a field called bool6. name is not b , number is biger than 2

Page 81: node.js workshop- node.js databases

81

A possible solutionfunction get(query) { db.collection('querys').find(query).toArray(function (err, result) { if (err) throw err; console.log('Query = ' + JSON.stringify(query)); console.log(result); });}

Page 82: node.js workshop- node.js databases

82

Resultquery ={name:'a'};

[ { _id: 537623665e7e2f181746dbd3, name: 'a', number: 2 }, { _id: 537623665e7e2f181746dbd2, name: 'a', number: 1 }, { _id: 537623665e7e2f181746dbd4, name: 'a', number: 3 } ]

Page 83: node.js workshop- node.js databases

83

ResultQuery = {"$and":[{" name":"a"},{"number":3}]} [ { _id: 537623665e7e2f181746dbd4, name: 'a', number: 3 } ]

Page 84: node.js workshop- node.js databases

84

ResultQuery = {"$or":[{"name":"a"},{"number":3}]} [ { _id: 537623665e7e2f181746dbd3, name: 'a', number: 2 }, { _id: 537623665e7e2f181746dbda, name: 'c', number: 3, bool: false }, { _id: 537623665e7e2f181746dbd2, name: 'a', number: 1 }, { _id: 537623665e7e2f181746dbd4, name: 'a', number: 3 }, { _id: 537623665e7e2f181746dbd7, name: 'b', number: 3 } ]

Page 85: node.js workshop- node.js databases

85

ResultQuery = {"number":{"$lt":2}} [ { _id: 537623665e7e2f181746dbd5, name: 'b', number: 1 }, { _id: 537623665e7e2f181746dbd8, name: 'c', number: 1 }, { _id: 537623665e7e2f181746dbd2, name: 'a', number: 1 } ]

Page 86: node.js workshop- node.js databases

86

ResultQuery = {"bool":{"$exists":true}} [ { _id: 537623665e7e2f181746dbda, name: 'c', number: 3, bool: false } ]

Page 87: node.js workshop- node.js databases

87

ResultQuery = {"$and":[{"name":{"$ne":"b"}},{"number":{"$gt":2}}]}

[ { _id: 537623665e7e2f181746dbda, name: 'c', number: 3, bool: false }, { _id: 537623665e7e2f181746dbd4, name: 'a', number: 3 } ]