Home  >  Article  >  Web Front-end  >  Node.js connects to mongoDB database to quickly build your own web service_node.js

Node.js connects to mongoDB database to quickly build your own web service_node.js

WBOY
WBOYOriginal
2016-05-16 15:05:051813browse

1. Write in front

Everyone wants to be a full-stack coder. As a web front-end developer, the simple way to full-stack seems to be node.js. I learned node.js some time ago, and let’s talk about how novices can quickly build their own web services and start the full-stack journey.

2. Install node.js

Anyone who has been exposed to back-end development knows that the service must be installed first. As a novice, you must choose the simplest visual installation (the next step is fool-proof, other methods will come naturally after you are familiar with the relevant operations), through the official website http://nodejs.org/dist/v0. 6.1/node-v0.6.1.msi Download the computer-adapted installation package (this is for windows, I can’t afford a mac), and then install it according to the boot. By default, it is installed under the C:Program Filesnodejs file. And add this directory to the PATH environment variable. To do this, right-click "My Computer" - "Properties" - "System Advanced" - "Advanced" - "Environment Variables" - select "Variable Name: PATH"; "Change Value: Add [C:Program" at the end Filesnodejs] (depending on your own installation directory)". Open cmd and run the command directly:

node -v can output the current version number. npm has been integrated into the node file, and then use npm install XXX to install the required plug-ins or modules.

3. Use express framework

After working for a while, I finally used the npm command to initialize, install the express framework, and then write hello world. It felt great. Why should you choose express framework? Of course it has its special features. The biggest fear for novices is that it is troublesome and easy to make mistakes. Of course express has taken this into consideration for us, so it provides a quick generator: express-generator

1. Use the command: npm install express-generator -g to install it globally

2. Use express command to generate project structure

express myapp where myapp is your project name

3. Enter the project file via cd myapp

Initialize dependent modules via npm install

Start the web server via set DEBUG=myapp & npm start

4. Open the http://localhost:3000/ URL in the browser to see the application.

The template engine used by default is jade, and this template has been configured in the project.

4. Introducing the express generator project

1. The organization 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 that it is generated by the configuration here when the project module is initialized.

3. app.js is the startup file of the project, which can be said to be the core of the project. Mainly write some public functions.

4. There is a www file without suffix under the bin file. This is the entry file of the project and configures the web service port and some monitoring events.

5. node_modules is the file module that the project depends on, and the packages imported later will also be placed in it, such as the mongoose module that connects to the database, which will be discussed in detail later.

6. Public is the static resource file set of the project. It is easy to see that pictures, css files, and js files are placed here.

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

8. Views is the template file of the project, which is the jade template engine. This template is very simple, but it also has many pitfalls. For example, the requirements for spaces are very strict. If there is one more space or one less space, an error will be reported. I have stepped on many Pitfalls, in fact, its performance is not very high, so it is better to use ejs.

5. Install mongoDB

1. Also download the msi file directly on the official website (http://www.mongodb.org/downloads)

2. Simply proceed to the next step to install. If there is a default, let it be the default. If there is a choice, select all.

3. Then configure the environment variables, which are the same as node and will not be described again, but you can put the middle picture, hahaha...

4. The next step is to start the mongoDB service

5. Pass the command: mongod --dbpath f:MongoDBdata where f:MongoDBdata is the file storage path. If you see the following information, it means success

6. MongoDB listens to port 27017. At the same time, open the browser and enter http://127.0.0.1:27017, you will see the following prompt:

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

7. Then, open a cmd and enter the mongo command to connect to the database. The following prompt will appear:

 2015-05-02T17:10:19.467+0800 I CONTROL Hotfix KB2731284 or later update is not installed, will zero-out data files MongoDB shell version: 3.0.2 connecting to: test

8. In this way, monogDB in the windows environment is successfully installed.

Supplement:

9. If you find it troublesome to use a command to open the service every time, you can write a batch file, that is, create a new file with the suffix .bat and write the following code:

start mongod --dbpath F:MongoDBdata

10. Of course, you can also start MongoDB as a service, but I think it is not very useful in the learning process. You can try it yourself. If necessary, I will make up for it later. .

11. If you find the command line difficult to use, I recommend a software with a graphical interface: MongoVUE, which is similar to navicat. It has a free version, which has fewer functions, but it is enough for the learning process

6. Using monogDB in node projects

1. Import the monogDB connection module. Express officially introduces the mongoskin module. I won’t go into this. Here is an introduction to installing it through mongoose

2. Execute the command npm install mongoose -save under the myapp project to save the installation to node_modules. You can also configure "mongoose": "^4.4.12" in package.json, and then command npm install to install.

3. In the app.js file

a. Import the mongoose module:

var mongoose = require('mongoose');
b. Create database connection

mongoose.connect('mongodb://localhost/myDB') //Connect to local database
4. Create a new folder schemas in the project root directory. This is the data set module. Create a new users.js file under the module

var mongoose = require('mongoose');

//申明一个mongoons对象
var UsersSchema = new mongoose.Schema({
 name: String,
 paw: String,
 meta: { 
  createAt: {
   type: Date,
   default: Date.now()
  },
  updateAt: {
   type: Date,
   default: Date.now()
  }
 }
})

//每次执行都会调用,时间更新操作
UsersSchema.pre('save', function(next) {
 if(this.isNew) {
  this.meta.createAt = this.meta.updateAt = Date.now();
 }else {
  this.meta.updateAt = Date.now();
 }

 next();
})

//查询的静态方法
UsersSchema.statics = {
 fetch: function(cb) { //查询所有数据
  return this
   .find()
   .sort('meta.updateAt') //排序
   .exec(cb) //回调
 },
 findById: function(id, cb) { //根据id查询单条数据
  return this
   .findOne({_id: id})   
   .exec(cb)
 }
}

//暴露出去的方法
module.exports = UsersSchema 

5. Add the modules file in the root directory. This is the data model module. Add the users.js file under the module

 var mongoose = require('mongoose')
 var UsersSchema = require('../schemas/users') //拿到导出的数据集模块
 var Users = mongoose.model('Users', UsersSchema) // 编译生成Movie 模型
 
 module.exports = Users

6. Add the routing controller code to the users.js file in the routes file

var express = require('express');
var mongoose = require('mongoose');//导入mongoose模块

var Users = require('../models/users');//导入模型数据模块

var router = express.Router();

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

//查询所有用户数据
router.get('/users', function(req, res, next) {
 Users.fetch(function(err, users) {
  if(err) {
   console.log(err);
  }  
  res.render('users',{title: '用户列表', users: users}) //这里也可以json的格式直接返回数据res.json({data: users});
 })
})
module.exports = router;

7. Add users.jade under the views file

extends layout

block content
 h1= title //jade取值方式
 ul
 each user in users //jade模版的遍历方式
  li
  h4 #{user.name} 
  span #{user.paw}


8. Finally, open the URL in the browser: http://localhost:3000/users/users to check the effect. At this point, a project from database to front-end display is completed.

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn