Node+express+mongoose Fast Build Movie website

Source: Internet
Author: User
Tags mongodb string format

This article is mainly to learn Scott's building a site introduction one of the study notes. 1. Build the Environment

Using the node's NPM tool for the frames or classes that need to be used at the front and rear of the installation, the framework used to build the movie site is as follows:

Back end: (Install with NPM)

Mongoose: Tools for quick modeling of MongoDB

Mongodb:nosql Database

Jade: client's template engine

Moment.js: Date format

Front End: (NPM installation Bower,bower install other front-end libraries)

jquery Class Library

Bootstrap Framework specific actions: first go to the root of the new project, and then use NPM to install

NPM install Express//background frame will be used

NPM Install Body-parser//New Express does not have its own, used to parse the contents of the body of the client request, the internal use of JSON encoding processing, URL encoding processing and file upload processing.

NPM Install jade//template engine usage

NPM install underscore//underscore encapsulates commonly used JavaScript object manipulation methods to improve development efficiency

NPM Install moment//Time format processing class

NPM Install Mongoose

NPM Install Bower-g

Bower Install Bootstrap


To facilitate resource files in the project, we create a new folder public in the root directory, create a new Libs folder in public, and copy the files in bwer_components. 2. Project page and function analysis


The main function of the project is: to show the home page index of all movies, click on a movie in the home page to view the details of the detail, there is a film input information on the interface admin, as well as the list of movie lists, you can delete the movie, modify and other operations. 3. Write the front page

According to functional requirements, the use of Jade way to write front-end pages, mainly in views of the file. The includes is the public part of pages in pages, Layout.jade is the layout of the page.


4. Construction of back-end data Model

Define the model movie in the project, where you define a schema:movieschem, and when you define a schema, you can also set some defaults, validate something, but ignore it first.

var mongoose = require (' Mongoose ')

//skeleton template
var movieschema = new Mongoose. Schema ({
    doctor:string,
    title:string,
    language: String,
    country:string,
    year:number,
    summary: String,
    flash:string,
    poster:string,
    meta:{
        createat:{
            type:d Ate,
            default:date.now ()
        &NBSP},
        updateat:{
             type:date,
            default:date.now ()
         }
    
})

var Movie = Mongoose.model (' Movie ', Movieschema)//In this sentence, the first argument is quite important, it is to give Movieschema this schema, defines a name Movie

Module.exports = Movie//use Module.exports to export it to make it externally available
use of the 5.express framework

To create the server:

var express = require (' Express ')
var path = require (' path ')

Set port, Process global variable
var port = Process.env.PORT | | 3000


Database Connection class var Mongoose = require (' Mongoose ')
var _ = require (' underscore ')
var Movie = require ('./models/movie ')


Connection database: Connection string format is mongodb://host/database name
Mongoose.connect (' Mongodb://localhost/imooc ')

Start the Web server

var express = require (' Express ')
var app = Express ()


Assign an instance to a variable, configure the view
App.set (' views ', './views/pages ')
Set the default template engine

App.set (' View engine ', ' Jade ')


form data formatting

var bodyparser = require (' Body-parser ')

App.use (bodyparser.urlencoded ({extended:true}))


Set Resource Path
App.use (Express.static (Path.join (__dirname, ' public '))
App.locals.moment = require (' moment ')
Listening port
App.listen (Port)


Writing URL Routing

/home Page index page routing
App.get ('/', function (req,res) {
Movie.fetch (function (err,movies) {
if (err) {
Console.log (ERR)
}

Res.render (' index ', {
Title: ' Immoc Home ',
Movies:movies
})
})
})

Details Page Detail Routing
App.get ('/movie/:id ', function (req,res) {
var id = req.params.id

Movie.findbyid (Id,function (Err,movie) {
Res.render (' detail ', {
Title: ' Immoc ' +movie.title,
Movie:movie
})
})
})

Admin Pages Admin Page Route
App.get ('/admin/movie ', function (req,res) {
Res.render (' admin ', {
Title: ' Immoc Background entry page ',
movie:{
Title: ',
Doctor: ',
Country: ',
Year: ',
Poster: ',
Flash: ',
Summary: ',
Language: '
}
})
})

Admin Update Movie
App.get ('/admin/updat:id ', function (req,res) {
var id = req.params.id

if (ID) {
Movie.findbyid (Id,function (Err,movie) {
Res.render (' admin ', {
Title: ' Immoc Background update page ',
Movie:movie
})
})
}
})

Admin Post Movie
App.post ('/admin/movie/new ', function (req,res) {
var movieobj = Req.body.movie
var id = req.body.movie._id
var _movie

if (id!== ' undefined ') {
Movie.findbyid (Id,function (Err,movie) {
if (err) {
Console.log (ERR)
}

_movie = _.extend (movie,movieobj)

_movie.save (function (Err,movie) {
if (err) {
Console.log (ERR)
}

Res.redirect ('/movie/' +movie._id)
})

})
}else{
_movie = new Movie ({
Doctor:movieObj.doctor,
Title:movieObj.title,
Country:movieObj.country,
Language:movieObj.language,
Year:movieObj.year,
Poster:movieObj.poster,
Summary:movieObj.summary,
Flash:movieObj.flash
})

_movie.save (function (Err,movie) {
if (err) {
Console.log (ERR)
}

Res.redirect ('/movie/' +movie._id)
})
}
})

Routing of List page
App.get ('/admin/list ', function (req,res) {
Movie.fetch (function (err,movies) {
if (err) {
Console.log (ERR)
}

Res.render (' list ', {
Title: ' Immoc List page ',
Movies:movies
})
})
})

List Delete Movie
App.delete ('/admin/list ', function (req,res) {
var id = req.query.id

if (ID) {
Movie.remove ({_id:id},function (Err,movie) {
if (err) {
Console.log (ERR)
}else{
Res.json ({success:1})
}
})
}
})


6. The project starts to run

Go to root directory, run node App.js

Open the index page in browse: http://localhost:3000

Source code for the entire project: code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.