Get started with Node. js, Express, Ejs, Mongodb server, and application development, node. jsmongodb

Source: Internet
Author: User
Tags connect mongo install mongodb mongodb server install node node server

Get started with Node. js, Express, Ejs, Mongodb server, and application development, node. jsmongodb

This article is a guide for front-end developers to build a Node from scratch. in js, Express, Jade, and Mongodb server, the reason why Jade is changed to Ejs is that I think ejs is more in line with the habits of WEB programmers, more specifically, it should be more in line with the use habits of PHP and ASP programmers. Okay. Let's just start the tutorial.

Part 1-15-minute Installation

If you are learning from scratch, take the time to build the environment first. This is not difficult. I use Win8, so it seems a little different from those using Mac, Ubuntu, or other * nix systems, but it is roughly the same.

Step 2-install Node. JS

This is easy. Go to the Node. js official website and click the big Install button in green. It will automatically detect your system and give you a download of the correct installation file. (If not, click Download to select the desired Download ). Run the installer. You have installed Node. js and NPM (Node Package Manager) to easily install various useful packages into Node.

Step 2-install Express

Now we have run the Node, and we need something to create a usable site. Next we need to install Express, which is a framework that changes Node from an original application to a Web server that we usually use. We need to start with Express because we need the scaffolding feature provided by Express. Run the following command:
Copy codeThe Code is as follows:
C: \ node> npm install-g express

In this way, Express is correctly installed in our Node and has been set to globally available. You will see a bunch of output in the command line window, most of which are http 304 and GET requests, which is normal. Express should have been installed and available.

Step 2-create an Express Project

We are going to use Express and Ejs, but it is not used for CSS preprocessing. We will write some CSS. We need to use Ejs or other template engines to process Node and Express data. If you have HTML, it is not difficult for Ejs. Keep in mind that you need to concentrate, otherwise things may be prone to errors.

Now, in the same command line window, enter:
Copy codeThe Code is as follows:
C: \ node> express-sessions nodetest1

Press enter and you will see a bunch of things like this:
Copy codeThe Code is as follows:
C: \ node> express -- sessions nodetest1
Create: nodetest1
Create: nodetest1/package. json
Create: nodetest1/app. js
Create: nodetest1/routes
Create: nodetest1/routes/index. js
Create: nodetest1/routes/user. js
Create: nodetest1/views
Create: nodetest1/views/index. ejs
Create: nodetest1/public/images
Create: nodetest1/public/javascripts
Create: nodetest1/public
Create: nodetest1/public/stylesheets
Create: nodetest1/public/stylesheets/style.css

Install dependencies:
$ Cd nodetest1 & npm install

Run the app:
$ Node app

Step 2-edit dependency

Now we have some basic project structures, but they are not complete yet. You will notice that the installation process of express creates a file named package. json in your nodetest1 directory and opens the file in a text editor. It should be long.
Copy codeThe Code is as follows:
{
"Name": "application-name ",
"Version": "0.0.1 ",
"Private": true,
"Scripts ":{
"Start": "node app. js"
},
"Dependencies ":{
"Express": "3.4.8 ",
"Ejs ":"*"
}
}

This is a standard JSON format file, indicating our application and its dependencies. We need to add something. For example, calling mongodb and Monk. Change the dependencies part to the following:
Copy codeThe Code is as follows:
"Dependencies ":{
"Express": "3.4.8 ",
"Ejs ":"*",
"Mongodb ":"*",
"Monk ":"*"
}

Step 2-install dependency

Now we have defined the project dependencies. * Will tell NPM "install the latest version ". Return to the command line window, enter the nodetest1 directory, and enter:
Copy codeThe Code is as follows:
C: \ node \ nodetest1> npm install

It outputs a bunch of things. This is because it directly reads the modified JSON file, recognizes the dependencies, and installs required files. After NPM is installed, you should have a node_modules directory that contains all the dependent files required by our project.

Now we have a complete function App and can run it. Let's try it! Make sure that your current directory is the nodetest1 directory. Enter:
Copy codeThe Code is as follows:
C: \ node \ nodetest1> node app. js

After you press enter, you will see:
Copy codeThe Code is as follows:
Express server listening on port 3000

Great. Open your browser and enter http: // localhost: 3000. You should be able to see a welcome page of Express.

Now you have run your own Node JS WebServer with the Express engine and Ejs HTML template engine. Not very difficult, right?

Part 1-now, let's write "Hello, World !" Right

Open your frequently-used Text editor or other IDE. I personally prefer Sublime Text. Open app. js in the nodetest1 directory. This file is the core of your App. You should see the following content:
Copy codeThe Code is as follows:
Var express = require ('express ');
Var routes = require ('./routes ');
Var user = require ('./routes/user ');
Var http = require ('http ');
Var path = require ('path ');

This just defines a bunch of JavaScript variables and points to some packages and dependencies, node functions, and routes. A Routes (route) is equivalent to a set of Models and Controllers in MVC. It forwards requests and contains processing logic. Express has already created all these things for us. Now we ignore user route and start to write the top-level route (controlled by routes \ index. js ).

At the end of the above file, write:
Copy codeThe Code is as follows:
Var app = express ();

This sentence is crucial. It instantiated Express and assigned the app variable to us. This variable will be used to configure a bunch of Express parameters in the following content. Continue input:
Copy codeThe Code is as follows:
// All environments
App. set ('Port', process. env. port | 3000 );
App. set ('view', path. join (_ dirname, 'view '));
App. set ('view engine ', 'ejs ');
App. use (express. favicon ());
App. use (express. logger ('dev '));
App. use (express. bodyParser ());
App. use (express. methodOverride ());
App. use (app. router );
App. use (express. static (path. join (_ dirname, 'public ')));

Here, we set a port to find the views directory and use the template engine to process these views and other things. Pay attention to the last line, which tells Express to host static files in the public/directory as files in the top-level directory. For example, your image directory is stored in c: \ node \ nodetest1 \ public \ images \, but the actual access address is http: // localhost: 3000/images /.

Note: You need to set this line
Copy codeThe Code is as follows:
App. use (express. bodyParser ());

Change
Copy codeThe Code is as follows:
App. use (express. urlencoded ());

This is to ignore the warning information in the Node window during App running. It mainly involves some possible modifications to Express and its plug-ins in the future. If you do not make this modification, you will receive a bunch of warnings that the function will soon expire when running the program.

Then add:
Copy codeThe Code is as follows:
// Development only
If ('development' = app. get ('env ')){
App. use (express. errorHandler ());
}

In this way, you can perform some error checks during the development process.

Continue to add:
Copy codeThe Code is as follows:
App. get ('/', routes. index );
App. get ('/users', user. list );

This tells the Route entry which Route is used for processing when a URI request arrives. Note that the user variable is defined previously and is mapped to/routes/user. js. We will call the list function defined in this file. The user list is displayed here.

Continue to add:
Copy codeThe Code is as follows:
Http. createServer (app). listen (app. get ('Port'), function (){
Console. log ('express server listening on port' + app. get ('Port '));
});

Finally, create an http server and start it. This is almost the case.

(The above content is complete in the new template generated by express, and you do not need to write it yourself)

Now we can write something useful. We will not directly write "Hello World!" in our index page !", We will take this opportunity to learn how to use route routing and how the Ejs engine works. Add a line after the section app. get () in the app. js File above:

App. get ('/helloworld', routes. helloworld );
If you press ctrl + C in the command line window at this time to end the app. restart the js process and access http: // localhost: 3000/helloworld in a browser. You will receive an exciting node error and a bunch of crash prompts in the command line window. This is because we have not modified the route to process this path. Let's do this. In your editor, go to the routes directory, find index. js, and open it. It looks like this:
Copy codeThe Code is as follows:
/*
* GET home page.
*/

Exports. index = function (req, res ){
Res. render ('index', {title: 'express '});
};

Let's add a new page. I prefer to create an independent route file for each level-1 directory, but now we do not plan to create a complete directory structure for helloworld under views, so we will use index routing for the moment. Add at the end of the file:
Copy codeThe Code is as follows:
Exports. helloworld = function (req, res ){
Res. render ('helloworld', {title: 'Hello, World! '});
};

It is responsible for processing this URI request, but now we have no actual page for res. render to render, which is the work of Ejs. Go to your views directory, open index. ejs, and save it as a helloworld. ejs file. Now it looks like this:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Title> <% = title %> </title>
<Link rel = 'stylesheet 'href = '/stylesheets/style.css'/>
</Head>
<Body>
<H1> <% = title %> <P> Welcome to <% = title %> </p>
</Body>
</Html>

It should be easy to understand.
Save the file. In the command line window, press ctrl + c to interrupt app. js, and then enter node app. js to restart it. Tip: When you modify an ejs template file, you do not need to restart the server. But when you change a js file, such as app. js or a routing js file, you must restart the server to see the effect.

After the server is started, note that the server opens http: // localhost: 3000/helloworld. You should be able to see this beautiful interface:

Okay! Now we have a route to process our template and see what we want. Next we will make some models (data layer ).

Part 2-create a database and read data

Step 2-install Mongodb

Close the text editor and return to the command line window. Open http://mongodb.org/and download the notebook. Click the download link in the main menu to find the version suitable for your system. For 64-bit win8, download 64-bit * 2008R2 +. The downloaded file is a zip file. decompress it to c: \ mongo or c: \ program files \ mongo or somewhere else. This is not important. We store the data in our nodetest1 directory.

Step 2-run Mongod and mongo

Create a sub-directory data in our nodetest1 directory, enter the bin directory of your mongodb directory in the command line window, and enter:
Copy codeThe Code is as follows:
Mongod-dbpath c: \ node \ nodetest1 \ data

You will see that the mongo server is started. It takes some time to start for the first time because it needs to pre-allocate some hard disk space and other tasks. When it prompts "[initandlisten] waiting for connections on port 27017", it will be done. There is nothing else to do, and the server is already running. Now you need to open another command line window, enter the bin directory of the mongo directory, and enter
Copy codeThe Code is as follows:
Mongo

You will see some tips similar to this:
Copy codeThe Code is as follows:
C: \ mongo> mongo
MongoDB shell version: 2.4.5
Connecting to: test

At this time, if you look at the mongod window, you will see a prompt that a connection has been connected. We will use this command line client to manually process our database, but this is not necessary for our Web site.

Step 2-create a database

Don't worry about the above prompt for connecting to test. If you do not specify a database, mongo does not create a database named test unless you add a record. Let's create a database of our own. In the mongo command line window, enter:
Copy codeThe Code is as follows:
Use nodetest1

It will not create this database unless we insert some data into it.

Step 2-add some data

My favorite feature of MongoDB is that it uses JSON as the data structure, which means I am very familiar with this. If you are not familiar with JSON, read the relevant information first, which is beyond the scope of this tutorial.

We add some data to the collection. In this tutorial, we only have one simple database with two fields: Hou username and email. Our data looks like this:
Copy codeThe Code is as follows:
{
"_ Id": 1234,
"Username": "cwbuecheler ",
"Email": "cwbuecheler@nospam.com"
}

You can create your own _ id field value, but I think it is best to let mongo do this. It creates a unique value for each record. Let's see how it works. In the mongo window, enter:
Copy codeThe Code is as follows:
Db. usercollection. insert ({"username": "testuser1", "email": "testuser1@testdomain.com "})

Note: db is the nodetest1 database we created above, and usercollection is our collection, which is equivalent to a data table. Note that we do not need to create this collection in advance. It will be automatically created when it is used for the first time. OK. Press enter. If everything goes well, you will see ...... Nothing. This is not very good. input:
Copy codeThe Code is as follows:
Db. usercollection. find (). pretty ()

If you are curious, the pretty method will format the output content and add line feed indentation. It should display:
Copy codeThe Code is as follows:
{
"_ Id": ObjectId ("5202b481d2184d390cbf6eca "),
"Username": "testuser1 ",
"Email": "testuser1@testdomain.com"
}

Of course, the ObjectID you get should be different, and mongo will automatically generate one. If you have used the JSON interface service before, do you think it is very easy to call it on the web! Well, you are right.

Tip: as a formal service, you should not want all data to exist at the top level. For the mongodb data structure design, please refer to Google.

Now we have a piece of data. Let's add more points. In the mongo window, enter:
Copy codeThe Code is as follows:
Newstuff = [{"username": "testuser2", "email": "testuser2@testdomain.com" },{ "username": "testuser3", "email": "testuser3@testdomain.com"}]
Db. usercollection. insert (newstuff );

Note that multiple data entries are transmitted to the collection at a time through one data entry. Easy! Use the find command above to view the three data items.

Now we can integrate the web servers and databases we have built.

Step 2-connect mongo to node

Now let's create a page to display the records in the database into a beautiful table. Here is the HTML content we prepare to generate:
Copy codeThe Code is as follows:
<Ul>
<Li> <a href = "mailto: testuser1@testdomain.com"> testuser1 </a> </li>
<Li> <a href = "mailto: testuser2@testdomain.com"> testuser2 </a> </li>
<Li> <a href = "mailto: testuser3@testdomain.com"> testuser3 </a> </li>
</Ul>

I know this is not scientific, but you can understand it. We just want to build a simple database read/write program, not a complete website. First, we add a bit of content to app. js (the heart and soul of our program) so that we can connect to mongodb. Open c: \ node \ nodetest1 \ app. js and you will see at the top:
Copy codeThe Code is as follows:
Var express = require ('express ');
Var routes = require ('./routes ');
Var user = require ('./routes/user ');
Var http = require ('http ');
Var path = require ('path ');

Add it below:
Copy codeThe Code is as follows:
// New Code
Var mongo = require ('mongodb ');
Var monk = require ('monk ');
Var db = monk ('localhost: 27017/nodetest1 ');

These lines tell the app that we need to connect to MongoDB. We use Monk to take charge of this connection. Our database is located at localhost: 27017/nodetest1. Note that 27017 is the default port of mongodb. If you modify the port for some reason, record the port as well. View the bottom of the file:
Copy codeThe Code is as follows:
App. get ('/', routes. index );
App. get ('/users', user. list );
App. get ('/helloworld', routes. helloworld );

Add a line below:
Copy codeThe Code is as follows:
App. get ('/userlist', routes. userlist (db ));

This line tells the app that when the user accesses the/userlist path, we need to pass the db variable to the userlist route. However, we do not have a userlist route. Create one now.

Step 2-read and display mongo data

Open c: \ node \ nodetest1 \ routes \ idnex. js in your editor. There are two route options: index and hello world. Now let's add the Third One:
Copy codeThe Code is as follows:
Exports. userlist = function (db ){
Return function (req, res ){
Var collection = db. get ('usercollect ');
Collection. find ({},{}, function (e, docs ){
Res. render ('userlist ',{
"Userlist": docs
});
});
};
};

Well, it's a little complicated. A function is defined here to receive the db variable we passed in, and then call a page render that is the same as the previous two route. We told it to read the usercollection and perform a search. The returned data is saved in the docs variable. Once we read the content, we call render to render the userlist template page and pass the obtained docs variable as the userlist variable in the template engine.

Next we will create our Ejs template. Open index. ejs in the views directory, save it as userlist. ejs, and modify its HTML as follows:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Title> USERLIST </title>
<Link rel = 'stylesheet 'href = '/stylesheets/style.css'/>
</Head>
<Body>
<H1> Userlist <Ul>
<%
For (var I in userlist ){
%>
<Li> <a href = "mailto: <% = userlist [I]. email %> "> <% = userlist [I]. username %> </a> </li>
<% }%>
</Ul>
</Body>
</Html>

Save the file and restart the node server. I hope you still remember how to restart. Open your browser and access http: // localhost: 3000/userlist. You should be able to see this interface:

Click Submit. You will see an error "can't post to/adduser. Let's fix it.

Step 2-Create Your Database handler

As before, we modified app. js, then the route file, and then the ejs template. However, the ejs template is not required here, because we will jump after post. Add a line to the end of app. get () in app. js:
Copy codeThe Code is as follows:
App. post ('/adduser', routes. adduser (db ));

Note that this is app. post, not app. get. To set the route. Go back to routes/index. js and create our database insertion function. This is relatively large, so I suggest you write comments.
Copy codeThe Code is as follows:
Exports. adduser = function (db ){
Return function (req, res ){

// Get our form values. These rely on the "name" attributes
Var userName = req. body. username;
Var userEmail = req. body. useremail;

// Set our collection
Var collection = db. get ('usercollect ');

// Submit to the DB
Collection. insert ({
"Username": userName,
"Email": userEmail
}, Function (err, doc ){
If (err ){
// If it failed, return error
Res. send ("There was a problem adding the information to the database .");
}
Else {
// If it worked, set the header so the address bar doesn't still say/adduser
Res. location ("userlist ");
// And forward to success page
Res. redirect ("userlist ");
}
});

}
}

Obviously, you still need to perform a lot of verification in the real project. For example, the user name and email cannot be duplicated, and the email address must comply with certain format rules. But now we don't care about this. As you can see, when the database insertion is complete, let the user jump back to the userlist page, where they should see the newly inserted data.

Is this the best way?

Step 2-connect to the database and write data

Make sure your mongod is running! Restart your node server. Open http: // localhost: 3000/newuser in a browser. Enter some content and click Submit. If it succeeds, we should return to the userlist page and see the newly added data.

Now we have officially completed the use of Node. js, Exress, and Ejs to read and write data to the Mongodb database. We are a cool x programmer.

Congratulations, really. If you have carefully read this tutorial and carefully studied it, instead of simply copying code, you should have a complete concept of routes, views, read data, and write data. This is what you need to develop any other complete Web site! Whatever you think, I think it's really cool.

Part 2-next step

From now on, you have unlimited possibilities. You can look at Mongoose, another Node package that processes MongoDB databases. It is larger than Monk and has more functions. You can also look at Stylus, an Express CSS engine. You can Google Node Express Mongo Tutorial to see the following content. Study hard and study every day.

I hope this tutorial will be helpful. I wrote this because when I started learning, I really needed something like this, but I could not find it. If you have seen this, thank you very much!

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.