Working with Browser and Database (AngularJS and MongoDB)

I build a small web application where you can put the name of a person and their phone number in it. What I struggled a lot was using AngularJS and MongoDB to make the application. Basically, there typically 3 groups are at work in making my application: browser, database and controller. The controller is the middleman between the browser and database. Information and data are grabbed from the database by the controller and tells the browser how the information should be display. I will be showing post and get request between the database and controller and the controller to the browser.

This is typically how you want to set up your server using node and express:

//server.js
var express = require("express");
var app = express();
var mongojs = require("mongojs");
var db = mongojs("phonelist", ["phonelist"]);

Let’s pretend we have a database called, “phonelist”, which I created in mongo. To retrieve data from the database, I would do this in my server.js file:

//server.js
app.get('/phonelist', function(req, res) {
db.phonelist.find(function(err, docs) {
console.log(docs);
res.json(docs);
});

I want to do a GET request from the phonelist database and then send a response with the data to the controller. In my application, I wanted to make edits to my phone number list. Therefore, I needed to do a GET request to the browser. Now, I want to do a GET response from the controller to the browser. To do this, I would do this in the controller.js file:

$scope.edit = function(id) {
$http.get("/phonelist/" + id).success(function(response) {
$scope.contact = response;
});
};

Basically, it is saying, if the GET request from the database was successful, then place the response in the browser. More specifically, I will put that response in my html where the ng-model tag is located.

Now that we talked about going from database to browser, let’s go from browser to the database. In my application, I wanted to add numbers to the database. Therefore, I need to do a POST request to the controller. To do this, I would need to do:

$scope.addNumber = function() {
$http.post("/phonelist", $scope.contact).success(function(response) {
refresh();
});
};

After going to the controller, I would need to go from controller to the database. To do this, I would need to do:

app.post("/phonelist", function(req, res) {
db.phonelist.insert(req.body, function(err, doc) {
res.json(doc);
});
});

I am going to the phonelist database and inserting the new data from the browser to the database. This is pretty much the work flow from going from database to browser and browser to database. I hoped this was helpful to you. This is my complete work of the phone list application that I was working on: https://github.com/evo777/phone-list

Feel free to fork or clone it to your github or computer respectively. Also, feel free to play around with it.