node. JS (Express) connection MongoDB Getting Started Guide

Source: Internet
Author: User
Tags generator mongodb monitoring web services

First, write in front

Everyone wants to be a full stack of farmers, as a web front-end developers, to the full stack of simple road, it seems to be node. js. I learned about node. js a while ago to talk about how to quickly build your own Web services and start the whole stack.

Ii. installing node. js

People who come into contact with the backend developers know that the first thing to do is install the service. As a novice, you must choose the simplest visual installation (Fool-type Next, other ways, such as familiar with the relevant operation will be natural), through the official website Http://nodejs.org/dist/v0.6.1/node-v0.6.1.msi Download the installation package for your computer (this is windows, you can't afford a Mac), and then install it according to the boot installation, which is installed by default under the C:\Program Files\nodejs file, and adds the directory to the PATH environment variable. Specifically, right-click on "My Computer"-"Properties"-"System Advanced"-"advanced"-"Environment variables"-Select "Variable name: PATH"; "Change measure: Add" C:\Program files\nodejs "(depending on your installation directory) on the last side. Open cmd to run the command directly:

Node-v can output the current version number. The node file has been integrated with NPM and then installed with NPM install XXX for the required plugins or modules.

Iii. use of the Express framework

After a busy moment, finally can use the NPM command to initialize, install the Express framework, and then write a Hello world cool. Why choose the Express framework, of course, there is its special, for the novice is the most afraid of trouble is also prone to error. Express is of course for us to consider, so provides a quick generator: express-generator

1、通过命令:npm install express-generator -g 安装到全局

2、在用express 命令生成项目结构

  express myapp 其中的myapp是你的项目名称

3、通过cd myapp 进入项目文件中

  通过npm install 初始化依赖模块

  通过set DEBUG=myapp & npm start 启动web服务器

4、在浏览器中打开 http://localhost:3000/ 网址就可以看到这个应用了。

 默认情况下用的模版引擎是jade,项目里也已经配置好了这个模版,看看jade的使用语法,1190000000357534 这个的文档不错。express官方网站http://www.expressjs.com.cn/

Iv. Introduction to the Express Generator project

1. The body of the MyApp project is as follows:

2, Package.json This can be said to be the module management package, project information and module version number, in fact, you will find in the Project module initialization is the configuration here to find the generated.

3, App.js is the project's starting document, can be said to be the core of the project. Mainly write some public functions.

4, the bin file has a no suffix of the www file, which is the entry file of the project, configure the Web service port and some monitoring events.

5, Node_modules is the project's dependent file module, then the imported package will be placed in it, such as the Mongoose module connected to the database, will be detailed later.

6, public is the project's static resource file set, it is easy to see pictures, CSS files, JS files are placed here.

7. Routes is the routing module of the project, which already defaults the Index.js and user.js files. In fact, this also includes the general background language of the controller content, of course, in large projects can be separated.

8, Views is the project template file, is the Jade template engine, the template is very concise, but the pit is also more, such as the requirements of the space is very strict, a little more than a space will be error, have stepped on a lot of pits, in fact, its performance is not very high is not as good as with Ejs.

V. Installation of MongoDB

1, the same on the official website (http://www.mongodb.org/downloads) directly download the MSI file

2, the simple next step to install, there is a default to let its default, there is a choice of all selected

3, and then configure the environment variables, and node is no longer a statement, but you can put in the picture, hahaha ...

4. The next step is to start the MongoDB service

5, through the command: Mongod--dbpath f:\MongoDB\data where the f:\MongoDB\data is the file storage path, see the following information to illustrate the success

6, MongoDB monitoring is 27017 port, while opening the browser input http://127.0.0.1:27017, you will see the following prompt:

It looks like you is trying to access MongoDB over HTTP on the native driver port.

7, then, then open a cmd, enter the MONGO command link database, the following prompt appears:

2015-05-02t17:10:19.467+0800 I CONTROL Hotfix KB2731284 or later update is not installed, would zero-out data files MongoDB Shell version:3.0.2 connecting To:test

8, so the MONOGDB in Windows environment is installed successfully.

Add:

9, if you do not bother to open the service with a command every time, you can write a batch file, is to create a new suffix. bat file, write the following code:

Start Mongod--dbpath F:\MongoDB\data

10, of course, you can also be mongodb to serve the way to start, but I think in the process of learning is not very useful, small partners can try their own, if necessary, I will fill in the back.

11, if the command line is not good to use, recommend a software with graphical interface: Mongovue, and Navicat almost, it has a free version of the function is less, but the learning process is completely enough
Portal: http://www.mongovue.com/

Refer to: Installation 1190000002744306, Syntax http://www.cnblogs.com/xusir/archive/2012/12/24/2830957.html

Vi. using MONOGDB in the node project

1, Import monogdb connection module, express official Introduction is the Mongoskin module, this I will not say, here is introduced by Mongoose installation

2, under the MyApp project to execute the command npm install Mongoose-save installation saved to Node_modules, you can also configure "Mongoose": "^4.4.12" in Package.json, and then command NPM install Installation. Https://github.com/Automattic/mongoose

3. In the App.js file

A, import Mongoose module:

1 var mongoose = require (' Mongoose ');

B. Create a database connection

// connecting to a local database

4, in the project root directory to create a new folder schemas, this is a dataset module, under the module to create a new Users.js file

1 varMongoose = require (' Mongoose '));2 3 //Declare a Mongoons object4 varUsersschema =NewMongoose. Schema ({5 name:string,6 paw:string,7 Meta: {8 createat: {9 Type:date,Ten             default: Date.now () One         }, A updateat: { - Type:date, -             default: Date.now () the         } -     } - }) -  + //each execution is called, the time update operation -Usersschema.pre (' Save ',function(next) { +     if( This. IsNew) { A          This. Meta.createat = This. Meta.updateat =Date.now (); at}Else { -          This. Meta.updateat =Date.now (); -     } -  - next (); - }) in  - //static methods for queries toUsersschema.statics = { +Fetchfunction(CB) {//query all data -         return  This the . Find () *. Sort (' meta.updateat ')//Sort $ . EXEC (CB)//callbackPanax Notoginseng     }, -FindByID:function(ID, CB) {//query single data by ID the         return  This + . FindOne ({_id:id}) A . EXEC (CB) the     } + } -  $ //Methods of exposure $Module.exports = Usersschema

5, add modules file in root directory, this is the Data Model module, add users.js file under module

1 var mongoose = require (' Mongoose ')2var// Get the exported data set module 3  var//  build Movie model 45 module.exports = Users

6. Add the route controller code in the Users.js file in the routes file

1 varExpress = require (' Express ');2 varMongoose = require (' Mongoose '));//import Mongoose Module3 4 varUsers = require ('.. /models/users ');//import model data module5 6 varRouter =Express. Router ();7 8 /*GET users listing.*/9Router.get ('/',function(req, res, next) {TenRes.send (' respond with a resource '); One }); A  - //Query all user data -Router.get ('/users ',function(req, res, next) { theUsers.fetch (function(Err, users) { -         if(err) { - Console.log (err); -         }         + res.render (' users ', {title: ' User list ', users:users})//This can also return data Res.json ({data:users}) directly in JSON format; -     }) + }) AModule.exports = router;

7. Added Users.jade under Views file

1 extends Layout 2 3 Block Content 4   h1= Title//jade value method 5  ul6each    user in Users// How the Jade template is traversed 7      li8        h4 #{user.name}    9         Span #{user.paw}

8. Finally open the URL in the browser: http://localhost:3000/users/users, see the effect. Here a project from the database to the front end is complete.

Vii. Conclusion

As a technician, the habit of summarizing and sharing is to improve yourself and help others. The source of this issue to me after finishing will put on GitHub, want to first of the can be a private messages me. The node module will then continue to be updated, including MongoDB modules, asynchronous operation modules, bootstrap integration modules, ANGULARJS integration modules, and so on ...

node. JS (Express) connection MongoDB Getting Started Guide

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.