In today’s tutorial we’ll be looking at: Installing Python Installing PyMongo (Note: PyMongo is a python driver for MongoDB) ..and running mms-agent from your computer(localhost)
I’m using Windows 7 64-bit machine and the installation procedure are shown for the same.
Disclaimer: This is not a paid post and neither am I using any affiliate links in this post. I found MMS(MongoDB Management Service) incredibly useful and I wish I knew about it earlier. The monitoring and alerting services can save your applications reputation, and the backup service will literally save your application in disasters situations.
This installs easy_installer inside C:\Python27\Scripts folder. Easy installer helps in installing drivers. Step 3: Now install Pythons MongoDB driver: PyMongo, with the following command.
Step 5: Log into your MMS account, and download the MMS-AGENT. Extract the mms-agent files into a folder. In our case, we extract it to D:\Python\mms-agent Step 6: Now run the mms-agent with the following command
Step 7: Go to your mms account – Fill the form with the host name, port number and other details
Host Type: Standalone (for this example) Internal Hostname: 127.0.0.1 (ip address for localhost) Port: 27017 (default port used my MongoDB server) DB Username and DB Password: are optional
Now it’ll start to fetch the meta data metrics via your IP address, as the agent is installed on your local machine and it knows your network IP address.
Key things inside your account Events: restart, shut-down or downtime etc Alerts: To alert you in certain situations. You get emails for downtime etc, once setup. Backup: It’s a premium service, which costs a little – backup service is pay-as-you-go service billed via credit card. Users: You could invite people as admin or read only user. This way, you could bring in your team mates/colleagues to analyze and help you in performance tuning of your application. Dashboard: You can customize your dashboard to give you quick view of key aspects of your application is a rich web console. You could have RAM usage statistics or query performance metrics etc. Settings: Normal profile information: email id, password, phone verification etc.
Application Performance Checking with the query performance and your application behavior from the very beginning of application development is recommended. And MMS is a perfect solution for this. This is one of the main reasons for this video tutorial. Running MMS on production servers is easy. You’ve bunch of plugins pre-installed at your host, you just need to enable it and insert the secret keys provided to you inside mms-agent file. But I would recommend you to watch for your application behavior from as early as in its development stage.
Note: You should know the norms of your application behavior, so that you can notice when there is abnormalities. MMS helps you effectively do that.
MongoDB Management Service is free service for getting metrics and setting alerts. And you only pay, if you use backup service and you pay for it as you use it.
ul
each user in users
li
a(href='/user/#{user._id}') #{user.name}
ul
each user in users li a(href='/user/#{user._id}') #{user.name}
This displays list of all the users with their name, hyper-linked with their email id(present inside _id).
Adding Edit link view/show.jade
1
2
3
4
5
6
7
8
<h1>#{user.name}</h1>
ul
li Age: #{user.age}
li Email: #{user._id}
ul
li
a(href="/user/#{user._id}/edit") Edit
<h1>#{user.name}</h1>
ul li Age: #{user.age} li Email: #{user._id}
ul li a(href="/user/#{user._id}/edit") Edit
This adds Edit link below each individual user information.
Edit Form view/edit-form.jade
1
2
3
4
5
6
7
8
9
<h1>Editing #{user.name}'s profile!</h1>
form(method="POST", action="/user/#{user._id}")
input(type="hidden", name="_method", value="PUT")
p Name:
input(type="text", name="name", value="#{user.name}")
p Age:
input(type="number", name="age", value="#{user.age}")
p
input(type="submit")
<h1>Editing #{user.name}'s profile!</h1>
form(method="POST", action="/user/#{user._id}") input(type="hidden", name="_method", value="PUT") p Name: input(type="text", name="name", value="#{user.name}") p Age: input(type="number", name="age", value="#{user.age}") p input(type="submit")
It shows a message letting know the user, which user’s information they are editing. Also it fills the previous values for name and age. You can find a hidden field with the name _method, which helps to override POST method, and facilitates PUT method.
Here id matches the param call, and using findById() method of mongoose, it fetches all the users present in the database. Once we call next(), it passes the control to next level. At /user/:id/edit route, we render edit-form.jade file and pass it with user information, to be filled inside the form input fields.
Once the user makes changes to the values and submits the form, all the values are passed to /user/:id route. In /user/:id route, we call update() method and specify which user information has to be updated in its first parameter, in second parameter we specify all the fields to be updated, and the third parameter is a callback method and it only takes error object as argument.
Syntax of findByIdAndUpdate() method is same as that of update(), only difference is, findByIdAndUpdate() returns the result object as well as error object to the callback method. We can make use of result object to our advantage – in our above example, I’m simply illustrating the concept by logging the result object on to the console window.
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect('mongodb://localhost/Company');
var Schema = new mongoose.Schema({
_id : String,
name: String,
age : Number
});
var user = mongoose.model('emp', Schema);
app.get('/user/:id/edit', function(req, res){
res.render('edit-form', {user: req.userId});
});
app.put('/user/:id', function(req, res){
user.findByIdAndUpdate({_id: req.params.id},
{
name: req.body.name,
age : req.body.age
}, function(err, docs){
if(err) res.json(err);
else
{
console.log(docs);
res.redirect('/user/'+req.params.id);
}
});
});
app.param('id', function(req, res, next, id){
user.findById(id, function(err, docs){
if(err) res.json(err);
else
{
req.userId = docs;
next();
}
});
});
app.get('/user/:id', function(req, res){
res.render('show', {user: req.userId});
});
app.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
else res.render('index', {users: docs})
});
});
app.post('/new', function(req, res){
new user({
_id : req.body.email,
name: req.body.name,
age : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else res.redirect('/view');
});
});
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect('mongodb://localhost/Company');
var Schema = new mongoose.Schema({
_id : String,
name: String,
age : Number
});
var user = mongoose.model('emp', Schema);
app.get('/user/:id/edit', function(req, res){
res.render('edit-form', {user: req.userId});
});
app.put('/user/:id', function(req, res){
user.findByIdAndUpdate({_id: req.params.id}, { name: req.body.name, age : req.body.age }, function(err, docs){ if(err) res.json(err);
else
{ console.log(docs); res.redirect('/user/'+req.params.id); } });
});
app.param('id', function(req, res, next, id){
user.findById(id, function(err, docs){
if(err) res.json(err);
else
{
req.userId = docs;
next();
}
});
});
app.get('/user/:id', function(req, res){
res.render('show', {user: req.userId});
});
app.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
else res.render('index', {users: docs})
});
});
app.post('/new', function(req, res){
new user({
_id : req.body.email,
name: req.body.name,
age : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else res.redirect('/view');
});
});
var server = http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port'));
});
/ for new entries /view for viewing all the users /user/:id to see individual user information /user/:id/edit to edit individual user information
Note: In real-world applications, it would make sense if only you are allowed to edit and update your data. To accomplish this – once the user logs in, store her _id value in a session variable. While the user issues an edit/update for a particular id, make sure the id she is requesting for edit/update matches with that present in the session variable!
In most modern-day applications we’ll need to show particular user information on their respective profile page. In today’s video tutorial, we’ll show you just that.
This is all very important – with that, retrieving single user information upon request is most common thing in modern-day web applications. So lets learn that today.
Here we’re creating a route for /user/:id We pass id of the user as first parameter to find() method. Once it retrieves that particular users information, we assign the first object in the result to user object and pass it on to show.jade template file.
Note: find() returns array of objects as result. But in fact, since we’re retrieving single user information in above case, we always get single object inside the result array. Thus, we assign docs[0] to user object.
In param we must match the param name – in above example snippet, name is id Also we’re using findById() method which is a method by mongoose module. It’s comparatively faster than find() method. findById() returns a single object, hence we can directly use it.
Here we fetch the particular user information and if successful, we copy the result object into req.userId variable, and call next(), which passes the control to next level, where it renders the result on show.jade template file.
What’s the use of the data in database, if we can’t fetch it and display on a web page! Today’s video tutorial concentrates on fetching data out of our mongoDB collection and displaying it on the web page.
Once the user visits /view route, she will be presented with all the registered users information. Inside /view route, we fetch all the user information by using mongoDB’s find() method. find() takes 2 parameters – first parameter is an object with condition, second parameter is a callback method. If we pass in empty object as first parameter, it means, fetch all the data – similar to SELECT * in sql.
If find() could successfully fetch the data out of mongoDB collection, it renders index.jade file and passes an object to it – which contains information of all the fetched users.
Template To Display User Information view/index.jade
1
2
3
ul
each user in users
li #{user.name}: #{user.age}: #{user._id}
ul
each user in users li #{user.name}: #{user.age}: #{user._id}
Observe the find() methods first parameter. Now we are passing _id to it, which means, it has to find and retrieve only the information related to the user with that _id.
Full Code To Insert And Fetch Data into/from MongoDB app.js
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect('mongodb://localhost/Company');
var Schema = new mongoose.Schema({
_id : String,
name: String,
age : Number
});
var user = mongoose.model('emp', Schema);
app.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
else res.render('index', {users: docs});
});
});
app.post('/new', function(req, res){
new user({
_id : req.body.email,
name: req.body.name,
age : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else res.redirect('/view');
});
});
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect('mongodb://localhost/Company');
var Schema = new mongoose.Schema({
_id : String,
name: String,
age : Number
});
var user = mongoose.model('emp', Schema);
app.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
else res.render('index', {users: docs});
});
});
app.post('/new', function(req, res){
new user({
_id : req.body.email,
name: req.body.name,
age : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else res.redirect('/view');
});
});
var server = http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port'));
});
To make this work, go to Save data To MongoDB: Node.js tutorial page and copy the index.html page code and create one for your project and put it inside public directory. Now you can directly access root(html form), enter user information and submit, which redirects to /view route, wherein you get the information of all the registered users.
Note: Make sure MongoDB server is running and turned on, when you start Node.js server and access your application from web browser.
Note: Save() is a higher lever method. It checks to see if the object we’re inserting is already present in our collection, by checking the _id value we’re inserting. _id field(which is a primary key in MongoDB document) – If there is no matching _id field in a document, it’ll call insert method and insert the data. And if the data being entered has no _id value, insert() method will create _id value for us, and insert the data into the collection. – If _id matches to any document in our collection, it’ll use update() instead to update the previously present data with the new data entered by the user.
Form To Facilitate User To Enter Her Details ..or Registration Form public/index.html
Here we have 3 input fields(for email, name and age) and a submit button. Since we’re posting these data to /new (in the action field of the form), we need to create /new route.
By using bodyParser() middleware, we get the data from the form, parse it and assign the values to corresponding keys, by creating a new user.
Note:user is a model object in our example. We also chain save method with new user object. Save() method takes a callback method as argument. The callback method takes 2 arguments – error and document. We check, if there are any errors while inserting the data, if so, we output the error object on to the screen. If the insertion was successful, we display “Successfully inserted!” message.
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect('mongodb://localhost/Company');
var Schema = new mongoose.Schema({
_id : String,
name: String,
age : Number
});
var user = mongoose.model('emp', Schema);
app.post('/new', function(req, res){
new user({
_id : req.body.email,
name: req.body.name,
age : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else res.send('Successfully inserted!');
});
});
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect('mongodb://localhost/Company');
var Schema = new mongoose.Schema({
_id : String,
name: String,
age : Number
});
var user = mongoose.model('emp', Schema);
app.post('/new', function(req, res){
new user({
_id : req.body.email,
name: req.body.name,
age : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else res.send('Successfully inserted!');
});
});
var server = http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port'));
});
Here we’ve shown the configurations, middleware, mongoose connection, schema, model object, routes and out application server.