SlideShare a Scribd company logo
1 of 34
Download to read offline
Be MEAN
Criando aplicações com MongoDb, Express,
AngularJs e Node.js
github.com/suissa
about.me/suissa
@osuissa
C++
JSON/BSON
Replica
Sharding
GridFS
Map/Reduce
V8
C/C++
I/O Async
Event Drive
MVC
Routes
Templates
Directives
Dependency Injection
Two Way Data-binding
Organização dos arquivos
app.js
package.json
modules/
db/
public/
routes/
views/
package.json
{
"name": "application-name"
, "version": "0.0.1"
, "private": true
, "dependencies": {
"express": "3.0.0"
, "jade": ">= 0.0.1"
, "mongo": "*"
, "mongoose": "*"
}
}
app.js
/**
* Module dependencies.
*/
var express = require('express'),
routes = require('./routes'),
api = require('./routes/api');
var app = module.exports = express();
app.js
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public'));
app.use(app.router);
});
app.js
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true,
showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
app.js
// Routes
app.get('/', routes.index);
app.get('/user/:id, routes.user);
// JSON API
app.get('/api/user/:id, api.userGet);
app.post('/api/user, api.userPost);
app.put('/api/user, api.userPut);
app.delete('/api/user, api.userDelete);
// redireciona todas outras para o index
app.get('*', routes.index);
app.js
// Start server
app.listen(3000, function(){
console.log("Server rodando na porta 3000");
});
routes/api.js
/**
* Create user
*/
exports.userPost = function (req, res) {
var user = new User(req.body)
user.save(function (err) {
if (err) {
return res.render('users/signup', {
errors: utils.errors(err.errors),
user: user,
title: 'Sign up'
})
}
}
routes/api.js
exports.userGet = function (req, res, next, id) {
User
.findOne({ _id : id })
.exec(function (err, user) {
if (err)
return next(err);
else
return user;
})
}
public/js/myapp.js
'use strict';
angular.module('myApp', ['myApp.filters', 'myApp.
services', 'myApp.directives']).
config(['$routeProvider', '$locationProvider', function
($routeProvider, $locationProvider) {
$routeProvider.when('/user, {templateUrl: 'user',
controller: AppCtrl});
$routeProvider.when('/user/:id, {templateUrl: 'user',
controller: AppCtrl});
$routeProvider.otherwise({redirectTo: '/});
$locationProvider.html5Mode(true);
}]);
public/js/controllers.js
'use strict';
/* Controllers */
function AppCtrl($scope, $http, $routeParams) {
var id = $routeParams.id;
$http({method: 'GET', url: '/api/user/'+id}).
success(function(data, status) {
$scope.name = data.name;
$scope.msg = 'Usuário encontrado.';
}).
error(function(data, status {
$scope.msg = 'Usuário não encontrado!';
});
}
modules/db/user.js
/**
* Module dependencies.
*/
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/database_name);
var db = mongoose.connection;
modules/db/user.js
/**
* User Schema
*/
var UserSchema = new Schema({
name: { type: String, default: '' },
email: { type: String, default: '', unique: true },
username: { type: String, default: '' },
hashed_password: { type: String, default: '' },
salt: { type: String, default: '' },
authToken: { type: String, default: '' },
});
mongoose.model('User', UserSchema);

More Related Content

Similar to Be MEAN

iPhone - web development lotus notes domino
iPhone - web development lotus notes dominoiPhone - web development lotus notes domino
iPhone - web development lotus notes domino
dominion
 

Similar to Be MEAN (20)

Zero to Hipster with the M.I.K.E. Stack
Zero to Hipster with the M.I.K.E. StackZero to Hipster with the M.I.K.E. Stack
Zero to Hipster with the M.I.K.E. Stack
 
Building HTTP API's with NodeJS and MongoDB
Building HTTP API's with NodeJS and MongoDBBuilding HTTP API's with NodeJS and MongoDB
Building HTTP API's with NodeJS and MongoDB
 
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and ExpressMIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
 
RequireJS
RequireJSRequireJS
RequireJS
 
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJSMeteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
Meteoro de pegasuus! Desenvolvendo aplicações realtime com MeteorJS
 
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
 
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
Spring Data MongoDB 介紹
Spring Data MongoDB 介紹Spring Data MongoDB 介紹
Spring Data MongoDB 介紹
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web Application
 
Headless Drupal en pratique
Headless Drupal en pratiqueHeadless Drupal en pratique
Headless Drupal en pratique
 
Getting into ember.js
Getting into ember.jsGetting into ember.js
Getting into ember.js
 
Node.js with WebMatrix
Node.js with WebMatrixNode.js with WebMatrix
Node.js with WebMatrix
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
iPhone - web development lotus notes domino
iPhone - web development lotus notes dominoiPhone - web development lotus notes domino
iPhone - web development lotus notes domino
 
API Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015
API  Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015 API  Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015
API Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015
 
Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2Mobile App Development: Primi passi con NativeScript e Angular 2
Mobile App Development: Primi passi con NativeScript e Angular 2
 
Nodejs.meetup
Nodejs.meetupNodejs.meetup
Nodejs.meetup
 
Story about module management with angular.js
Story about module management with angular.jsStory about module management with angular.js
Story about module management with angular.js
 
Sails.js Intro
Sails.js IntroSails.js Intro
Sails.js Intro
 

More from Suissa

Secot banco de dados no sql de código aberto
Secot   banco de dados no sql de código abertoSecot   banco de dados no sql de código aberto
Secot banco de dados no sql de código aberto
Suissa
 
Flisol - Nodejs e MongoDb o casamento perfeito
Flisol - Nodejs e MongoDb o casamento perfeitoFlisol - Nodejs e MongoDb o casamento perfeito
Flisol - Nodejs e MongoDb o casamento perfeito
Suissa
 
7 masters wordpress - advanced queries
7 masters   wordpress - advanced queries7 masters   wordpress - advanced queries
7 masters wordpress - advanced queries
Suissa
 
Fisl banco de dados no sql de código aberto
Fisl   banco de dados no sql de código abertoFisl   banco de dados no sql de código aberto
Fisl banco de dados no sql de código aberto
Suissa
 
Curso mongo db com php
Curso mongo db com phpCurso mongo db com php
Curso mongo db com php
Suissa
 
Html5 storage api
Html5 storage apiHtml5 storage api
Html5 storage api
Suissa
 

More from Suissa (20)

ES6 funcional TDC - Suissa
ES6 funcional TDC - SuissaES6 funcional TDC - Suissa
ES6 funcional TDC - Suissa
 
TypeScript - Olhe teu tipo, script slides
TypeScript - Olhe teu tipo, script slidesTypeScript - Olhe teu tipo, script slides
TypeScript - Olhe teu tipo, script slides
 
Mongoose - Melhores práticas usando MongoDB e Node.js
Mongoose - Melhores práticas usando MongoDB e Node.jsMongoose - Melhores práticas usando MongoDB e Node.js
Mongoose - Melhores práticas usando MongoDB e Node.js
 
Atomic design
Atomic design Atomic design
Atomic design
 
Palestra node.js
Palestra   node.js Palestra   node.js
Palestra node.js
 
Be MEAN JSConf Uruguay - Suissa
Be MEAN JSConf Uruguay - SuissaBe MEAN JSConf Uruguay - Suissa
Be MEAN JSConf Uruguay - Suissa
 
Atomic design
Atomic designAtomic design
Atomic design
 
Devcast node.js e mongo db o casamento perfeito
Devcast   node.js e mongo db o casamento perfeitoDevcast   node.js e mongo db o casamento perfeito
Devcast node.js e mongo db o casamento perfeito
 
Secot banco de dados no sql de código aberto
Secot   banco de dados no sql de código abertoSecot   banco de dados no sql de código aberto
Secot banco de dados no sql de código aberto
 
Flisol - Nodejs e MongoDb o casamento perfeito
Flisol - Nodejs e MongoDb o casamento perfeitoFlisol - Nodejs e MongoDb o casamento perfeito
Flisol - Nodejs e MongoDb o casamento perfeito
 
Ph pn rio 2012 - conheça seu primeiro banco de dados orientado a grafos
Ph pn rio 2012 - conheça seu primeiro banco de dados orientado a grafosPh pn rio 2012 - conheça seu primeiro banco de dados orientado a grafos
Ph pn rio 2012 - conheça seu primeiro banco de dados orientado a grafos
 
Javascript moderno
Javascript modernoJavascript moderno
Javascript moderno
 
DevDay - O elo perdido: sincronizando webapps
DevDay - O elo perdido: sincronizando webappsDevDay - O elo perdido: sincronizando webapps
DevDay - O elo perdido: sincronizando webapps
 
DevDay - MongoDb no mundo real - slides
DevDay - MongoDb no mundo real - slidesDevDay - MongoDb no mundo real - slides
DevDay - MongoDb no mundo real - slides
 
7 masters wordpress - advanced queries
7 masters   wordpress - advanced queries7 masters   wordpress - advanced queries
7 masters wordpress - advanced queries
 
Javascript moderno
Javascript modernoJavascript moderno
Javascript moderno
 
Fisl banco de dados no sql de código aberto
Fisl   banco de dados no sql de código abertoFisl   banco de dados no sql de código aberto
Fisl banco de dados no sql de código aberto
 
Mongo db no mundo real slides
Mongo db no mundo real   slidesMongo db no mundo real   slides
Mongo db no mundo real slides
 
Curso mongo db com php
Curso mongo db com phpCurso mongo db com php
Curso mongo db com php
 
Html5 storage api
Html5 storage apiHtml5 storage api
Html5 storage api
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Be MEAN