Mean stack novice navigation?

Time:2020-10-29

How do I use mean stack to build a simple app

Recently, I have been studying the development of mean stack, but the tutorials from Google are too scattered. There are express, restful interfaces and angular resource designs, but there is no complete set of mean. And mature frameworks such asmeteormeaniomeanjsIt’s not very suitable for beginners?.

Finally, through our own practice, we build this simple mean application and realize the basic crud operation?. From the back-end nodejs to the front-end angularjs, only the simplest and most convenient module is used. If you are also interested in mean development but have no idea, can you see how I connect each module of mean?.

live demo
Source code repository
Backend overview mongoose restful mlab express nodejs
Front end overview angularjs angular UI router angular resource bootstrap
Mongodb + Express + Angularjs + Nodejs == MEAN
For background information, please click

The directory structure is shown in the figure below

Mean stack novice navigation?

Back end construction

  1. Back end data model building model > movies.js

  2. Back end routes > route movies.js

  3. Database connection and server startup app.js

Front end construction

  1. Restful API design public > JS > public service.js

  2. The front end routing is public > JS > public app.js

  3. Data display template public > *. HTML


If you want to follow me, Download nodejs A kind of And install the following in the project package.json

package.json As follows, other versions are not guaranteed to work properly

    "angular": "^1.5.9",
    "angular-resource": "^1.5.9",
    "angular-ui-router": "^0.3.2",
    "body-parser": "^1.13.3",
    "bootstrap": "^3.3.7",
    "express": "^4.13.3",
    "mongoose": "^4.0.1"

Building back end API

1 movies.js Next, let’s build a data model. Our model only contains title, director and others?.
aboutdata model mongoose.Schema More settings

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var movieSchema = new  Schema({
  title: String,
  director: String
});

module.exports = mongoose.model('Movie', movieSchema);

2. In routes > 2 movies.js In the design of the routing API, use express, and the data model movie in the previous step.

var Movie = require('../model/movie');
var express = require('express');
//Import the module and assign it to router
var router = express.Router();

//Design route
router.route('/movies')
//Get all movies
  .get(function(req, res) {
    Movie.find(function(err, movies){
      if (err) {
        res.send(err);
      }
      res.json(movies);
    });
  })

//The familiar crud?
  .post(function(req, res) {
//Create a movie
    var movie = new Movie(req.body);
    movie.save(function(err) {
      if (err) {
        res.send(err);
      }
    })
  });

router.route('/movies/:id')
//Read a movie
  .get(function(req, res) {
    Movie.findOne({_id: req.params.id}, function(err, movie) {
      if (err) {
        res.send(err);
      }
      res.json(movie);
    });
  })

//Modify a movie
  .put(function(req, res) {
    Movie.findOne({_id: req.params.id}, function(err, movie) {
      if (err) {
        res.send(err);
      }
      for(prop in req.body){
        movie[prop] = req.body[prop];
      }
      movie.save(function(err) {
        if (err) {
          res.send(err);
        }
      });
    });
  })

.delete(function(req, res) {
//Delete a movie
    Movie.remove({
      _id: req.params.id
    }, function(err, movie) {
      if (err) {
        res.send(err);
      }
    });
  });

//Finally, the route is exported
 module.exports = router;

3. In app.js Under the connection database, establish the server. For databasemlabAfter all, free 500MB?

var express = require('express');
var bodyParser = require('body-parser');
var movies = require('./routes/movies');
var mongoose = require('mongoose');

var app = express();

app.use(express.static(__dirname + ''));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

//data api path
app.use(movies);

//This is my mlab database address, where mean is the account password
var connectionString = 'mongodb://mean:[email protected]:13668/mean';

//Connect to database
mongoose.connect(connectionString);
var conn = mongoose.connection;

//Test whether the database connection is normal
// conn.on('error', console.error.bind(console, 'connection error'))
// conn.once('open', function() {
//   console.log('database ready');
// });

//Start the server at localhost:8000 function
app.set('port', process.env.PORT || 8000);
app.listen(app.get('port'), function() {
  console.log('your app is running on port 8000');
})

Building front end API

1. In public > JS > 1 movies.js use$resourceBuild API

angular.module('App.service', [])
.factory('Movie', function($resource) {
  var $url = '/movies/:id';
  return $resource($url, {id: '@_id'}, {
//Since there is no update method for $resource, we need to build one ourselves
    update: {
      method: 'PUT'
    }
  });
})
//Window global modal box, which is used when deleting data
.service('popupService', function($window) {
    this.showPopup = function(message) {
      return $window.confirm(message);
    }
  });

2 app.js To enable the front-end routing, we use the angular UI router module

//Main module app, depending on ui.router Ngresource and the one we defined in the previous step App.service service
angular.module('App', ['ui.router', 'ngResource', 'App.service'])

//Start configuring routing and familiar crud?
  .config(function ($stateProvider) {
    $stateProvider.state('movies', {
      url: '/movies',
      templateUrl: 'public/movies.html',
      controller: function( $scope, $state, popupService, $window, Movie) {
      
      //Get all movies
        $scope.movies = Movie.query();
        $scope.deleteMovie = function(movie) {
          if ( popupService.showPopup ('delete? ')) {
          
          //Delete a movie
            movie.$delete();
            $window.location.href = '';
          }
        };
      }
    })
    
    .state('newMovie', {
      url: '/movies/new',
      templateUrl: 'public/movie-add.html',
      controller: function($scope, $state, $stateParams, Movie) {
        $scope.movie = new Movie();
        $scope.addMovie = function () {
        
        //Create a movie
          $scope.movie.$save();
          $state.go('movies');
        }
      }
    })
    
    .state('viewMovie', {
      url: '/movies/:id/view',
      templateUrl: 'public/movie-view.html',
      controller: function($scope, $stateParams, Movie) {
      
      //Read a movie
        $scope.movie = Movie.get({id: $stateParams.id});
      }
    })
    
    .state('editMovie', {
      url: '/movies/:id/edit',
      templateUrl: 'public/movie-edit.html',
      controller: function($scope, $state, $stateParams, Movie) {
        $scope.updateMovie = function() {
        
        //Update a movie
          $scope.movie.$update();
          $state.go('movies')
        };
        $scope.loadMovie = function() {
          $scope.movie = Movie.get({id: $stateParams.id});
        };
        $scope.loadMovie();
      }
    });
  })

//Default route
  .run(function($state) {
    $state.go('movies');
  });

3. After the routing design is completed, you can write the templateindex.htmlIntroduce various modules and style sheets

// index.html  Part of the content
  <div class="container">
      <div class="row top-buffer">
        <div class="col-md-8 col-xs-offset-2">
        
        //UI view is the display area of UI router. The templateurls in the state defined in the previous step are shown here
          <div ui-view></div>
        </div>
      </div>
    </div>

There are five other templates in public_ form.html Mainly responsible for C (movie) in crud- add.html )And U (movie)- edit.html )。 Both Cu templates reference_ form.html

//This is the U template movie- edit.html 
<form role="form" ng-submit="updateMovie()" class="form-horizontal">
  <div ng-include="'public/_form.html'"></div>
</form>
//This is the C template movie- add.html
<form role="form" ng-submit="addMovie()" class="form-horizontal">
  <div ng-include="'public/_form.html'"></div>
</form>

R template (movie)- view.html )Used to display a single movie data
The remaining D operations share the same template with the movies list movies.html

<a ui-sref="newMovie" class="btn-primary btn-lg nodecoration">Add New Movie</a>
<table class="table movietable">
    <tr>
        <td><h3>All Movies</h3></td>
        <td></td>
    </tr>
    <tr ng-repeat="movie in movies">
        <td>{{movie.title}}</td>
        <td>
            <a class="btn btn-primary" ui-sref="viewMovie({id:movie._id})">View</a>
            <a class="btn btn-danger"  ng-click="deleteMovie(movie)">Delete</a>
        </td>
    </tr>
</table>

So far, all the building work of this app has been completed. Each module in mean contains a huge amount of knowledge. This is just a very simple novice tutorial. We have experienced a JavaScript stack, which connects the front end and back end, designs simple API, links database, operates data, and displays templates.
Hope this tutorial will help you get into JavaScript stack?


Some learning materials
MEAN Stack Tutorial MongoDB ExpressJS AngularJS NodeJS
Build a blog with the MEAN stack
Creating RESTful APIs with Express 4
Creating a CRUD App in Minutes with Angular’s $resource

Recommended Today

SDS of redis data structure

SDS(simple dynamic string), simple dynamic string. S and it’s called hacking string. Where hack is stored is the length of the string and the remaining space in SDS. The implementation of SDS insds.cIn the middle. C language string uses a character array of length N + 1 to represent the string of length N, and […]