Node.js Connect MongoDB database to quickly build your own Web services _node.js

Source: Internet
Author: User
Tags generator mongodb install node

First, write in front

Everyone wants to be a full stack of farmers, as a Web front-end developers, to the whole stack of the simple road, it seems that is node.js. Some time ago to learn node.js, to talk about how to quickly build their own web services, open the entire stack of the road.

Second, install Node.js

People who are exposed to the end of the development know that the first thing to do is install the service. As a novice, is certainly the choice of the simplest visual installation (fool next, other ways such as familiar with the relevant operation will naturally after), through the official website Http://nodejs.org/dist/v0.6.1/node-v0.6.1.msi Download the computer adapter installation package (This is windows, can not afford Mac AH), and then based on the boot installation, the default installation under the C:\Program Files\nodejs file, and add the directory to the PATH environment variable. Concrete approach, right-click My Computer-Properties-system advanced-advanced-environment variables-Select variable name: PATH; Change measure: Add "C:\Program files\nodejs" (depending on your own installation directory) at the end of the list. Open cmd to run the command directly:

Node-v can output the current version number. The node file has already been integrated with NPM, then use NPM install XXX to install the required plug-ins or modules.

Iii. use of the Express framework

After a while, finally, the NPM command is used to initialize, install the Express framework, and then write Hello World cool. Why choose the Express framework, of course, there is its special, for the novice is the most afraid of trouble and error prone. Express of course for us to consider, so provide a quick generator: express-generator

1, through the command: NPM install express-generator-g installed to the global

2. Build the project structure with express command

Express MyApp One of the MyApp is your project name

3, through the CD MyApp into the project file

Initializing a dependency module via NPM install

Start a Web server with Set Debug=myapp & NPM start

4, in the browser open http://localhost:3000/Web site can see this application.

The template engine used by default is jade, and the template is already configured in the project.

Iv. Introduction to the Express Builder project

1, the MyApp project's organization is as follows:

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

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

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

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

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 project's routing module, which has default Index.js and User.js files. Here in fact also includes the general background language controller content, of course, in large projects can be separated.

8, views are the project template file, is Jade template engine, this template is very concise, but the pit is also more, such as the requirements of the space is very strict, a few more than a space will be an error, once stepped on a lot of pits, in fact, it is not very high performance is not as good as using Ejs it.

V. Installation of MongoDB

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

2, the simple next step to install, have the default let it default, have the choice of all selected

3, and then configure the environment variables, and node of the same no longer tired, but you can put in the picture, hahaha ...

4, the next is to start the MongoDB service

5, through the command: Mongod--dbpath f:\MongoDB\data f:\MongoDB\data is the file store path, see the following information to explain the success of the

6, MongoDB listening to the 27017 port, while opening the browser input http://127.0.0.1:27017, you will see the following prompts:

It looks like your are trying to access MongoDB over HTTP on the native driver port.

7, then, and then open a CMD, enter the MONGO command linked to the database, appear the following prompts:

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

8, so the Windows environment Monogdb installed successfully.

Add:

9, if you think that every time you use the command to open the service trouble, you can write a batch file, that is, a new suffix. bat file with 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 learning process is not very useful, small partners can try their own, if necessary, I will fill in the back.

11, if you think the command line is not good to use, recommend a graphical interface with the software: Mongovue, and Navicat almost, it has a free version of the function is less, but the learning process is completely enough

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 through the Mongoose installation

2. Execute the command under the MyApp project NPM install Mongoose-save installation to Node_modules, you can also configure "Package.json" in Mongoose: "^4.4.12" and then command NPM install Installation.

3, in the App.js file

A, import Mongoose module:

var mongoose = require (' Mongoose ');
b, creating a database connection

Mongoose.connect (' mongodb://localhost/mydb ')//Connect to local Database
4, in the project root directory new folder schemas, this is a dataset module, under the module new Users.js file

var mongoose = require (' Mongoose ');

Declare a Mongoons object
var usersschema = new Mongoose. Schema ({
 name:string,
 paw:string,
 meta: { 
  createat: {
   type:date,
   default:Date.now ()
  },
  updateat: {
   type:date,
   Default:Date.now ()}}}
)

//Every execution will be invoked, the time update operation
Usersschema.pre (' Save ', function (next) {
 if (this.isnew) {
  this.meta.createAt = This.meta.updateAt = Date.now ();
 } else {
  this.meta.updateAt = Date.now ();
 }

 Next ();
})

static method
Usersschema.statics = {
 Fetch:function (CB) {//query all data return this
  . Find
   ()
   . Sort ( ' Meta.updateat ')//Sort
   . EXEC (CB)//Callback
 },
 findbyid:function (ID, CB) {///According to ID query single data return this
   . FindOne ({_id:id})   
   . EXEC (CB)
 }
}

//exposure method
Module.exports = Usersschema 

5, add modules files in the root directory, this is the data Model module, under the module new Users.js file

 var mongoose = require (' Mongoose ')
 var usersschema = require ('.. /schemas/users ')//Get the exported DataSet module
 var users = Mongoose.model (' users ', Usersschema)//compile generation movie model
 
 Module.exports = Users

6, add the routing controller code in the Users.js file in the routes file

var express = require (' Express ');
var mongoose = require (' mongoose ');//import Mongoose module

var Users = require ('.. /models/users ')//Import model data module

var router = Express. Router ();

/* Get users listing. *
/Router.get ('/', function (req, res, next) {
 res.send (' respond with a resource ');
});

Query all user Data
router.get ('/users ', function (req, res, next) {
 Users.fetch (function (err, users) {
  if (err) {
   Console.log (err);
  }  
  Res.render (' users ', {title: ' User list ', users:users})///You can also directly return the data Res.json ({data:users}) in JSON format;}
)
Module.exports = router;

7, under the views file New Users.jade

Extends layout block

content
 h1= title//jade value Way
 ul each
 user in Users//jade template traversal way
  Li
  h4 #{ User.Name} 
  span #{user.paw}


8, finally open the Web site in the browser:http://localhost:3000/users/users, view the effect. Here a project from the database to the front end is complete.

The above is the entire content of this article, I hope to help you learn.

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.