Mongoose allows you to easily select resources by ID from your MongoDB. This is an important aspect to creating an API.
Server.js
'use strict';var expres = require('express');var mongoose = require('mongoose');mongoose.connect('mongodb://localhost/simple');var cors = require("cors");var personSchema = { firstName:String, lastName:String, email:String};//create a person model, and rename db as peoplevar Person = mongoose.model('Person', personSchema);var app = expres();app.use(cors());app.get('/people', function(request, response){ Person.find().select("firstName").exec(function(err, data) { response.json(200, data); })});app.get('/people/:id', function(request, response){ Person.findById(request.params.id, function(err, data) { response.send(data); });});app.listen(3000);
app.js:
/** * Created by Answer1215 on 12/9/2014. */'use strict';function MainCtrl(PeopleService) { var vm = this; vm.people = []; vm.selectedPerson = {}; vm.getPeople = PeopleService.getPeople().then(function(response) { vm.people = response.data; }); vm.selectPerson = function(person) { PeopleService.getSelectedPerson(person).then(function(response) { vm.selectedPerson = response.data; vm.selectedPerson.fullName = response.data.firstName + " " + response.data.lastName; }); }}function PeopleService($http) { var PeopleService = {}; PeopleService.getPeople = function() { return $http.get('http://localhost:3000/people'); } PeopleService.getSelectedPerson = function(person) { return $http.get('http://localhost:3000/people/'+person._id); } return PeopleService;}angular.module('app',[]) .controller('MainCtrl', MainCtrl) .service('PeopleService', PeopleService);
index.html
- { {person.firstName}}
{ {vm.selectedPerson.fullName}}
{ {vm.selectedPerson.email}}