使用Node.js 和 MongoDB 为app搭建后端简单教程 附代码

Use Node.js and MongoDB set up back-end for app on Mac

Introduction


This article is a brief introduction to wuse Node.js, Express, Mongoose build a back-end for mobile app. You can skip Introduction for a quik start.

Node.js

Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

we use Node.js because it’s easy to develop font-end with same language and many tutorials on the web.

MongoDB

MongoDB is an open-source, document database designed for ease of development and scaling.

MongoDB is often to coopreate with Node.js. In this article we will use a middleware called Mongoose to perform as MongoDB driver and easy to write CRUD operation.

Mongoose

Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.

Express

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Often to use with Node.js to organize your web application into an MVC architecture on the server side,Express.js basically helps you manage everything, from routes, to handling requests and views.

NPM

npm is Node’s package manager that will bring in all the packages we defined in package.json.

Getting started


File structure

  - app/
    ----- models/
    ---------- Account.js  // our account model
    - node_modules/     // created by npm. holds our dependencies/packages
    - package.json      // define all our node app and dependencies
    - server.js         // configure our application and create routes

Defining our Node Packages

package.json

{
    "name": "node-api",
    "main": "server.js",
    "dependencies": {
        "express": "~4.0.0",
        "mongoose": "~3.6.13",
        "body-parser": "~1.0.1",
        "morgan": "~1.0.0"
    }
}

express is the Node framework. mongoose is the ORM we will use to communicate with our MongoDB database. body-parser will let us pull POST content from our HTTP request so that we can do things like create an account, login etc.

Then open terminal on MacOS in the root of your application and type:

$npm install

To download Node.js and NPM.
And required node modules will down to the folder node_modules automatically.

Defining a Model

Before we can handle CRUD operations, we will need a mongoose Model. These models are constructors that we define. They represent documents which can be saved and retrieved from our database.
Mongoose Schema The mongoose Schema is what is used to define attributes for our documents.
Mongoose Methods Methods can also be defined on a mongoose schema.

module.exports = function(mongoose) {
  var crypto = require('crypto');// include encryption module
  var AccountSchema = new mongoose.Schema({// define the account data structure
    email:     { type: String, unique: true },
    password:  { type: String},
    phone:     { type: String},
    name:       {type: String},
    photoUrl:  { type: String},
    address: {type: String}
  });

  var Account = mongoose.model('Account', AccountSchema);
    var registerCallback = function(err) {
    if (err) {
      return console.log(err);
    };

    return console.log('Account was created');
  };
  //create an account
  var register = function(email, password, phone, name, res) {
    var shaSum = crypto.createHash('sha256');
    shaSum.update(password);//encrypt password before stored in database

    console.log('Registering ' + email);
    var user = new Account({
      email: email,
      password: shaSum.digest('hex'),
      phone: phone,
      name: name
    });
    user.save(registerCallback);
    res.send(200);
    console.log('Save command was sent');
  }  

  //export methods
    return {
    register: register,
    Account: Account
  }
}

In this data model, we define the Account with some data fileds and write two method to perform register function.

Server code

var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');//pretty logout for node.js
var crypto = require('crypto');
var http = require('http')//include for create http server
var app = express();// use express framwork
var mongoose = require('mongoose');
var Account = require('./app/models/Account')(mongoose);// import Account model
app.use(morgan('dev')); // log requests to the console 
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());// to parse json data
mongoose.connect('mongodb://localhost:27017/Server'); // connect to our database, 
//insert data into database "Server"
//config route events
var port = process.env.PORT || 8080; // set our port
var router = express.Router();
router.route('/')

    .get(function(req, res){
        res.send('hello world node.js~');
    });
// for GET request http://localhost:8080/api
router.route('/register')
    .get(function(req,res){
        res.render('reg', {
        title: 'register'
    });
    })
//for POST request http://localhost:8080/api/register
    .post(function(req, res) {
        console.log(req);   
        console.log(req.body.name);

        Account.register(req.body.email, req.body.password, req.body.phone, req.body.name, res);    
    });
app.use('/api', router);// append /api to every route we set
http.createServer(app).listen(port);//ceate a http server and listen to port:8080
console.log('http listen ' + port);

So far, we have create a node.js server.

这里写图片描述

Then type following command:

$node server.js

And type in your browser:

http://localhost:8080/api

You will see this in the brower:
这里写图片描述

MoogoDB

To download MongoDB.
Uncompress the zip file and the file structure like this:
这里写图片描述

To start MongoDB, use command line tool in to “bin” and type following command to run mongoDB process:

$./mongod --dbpath /file path to store your data

I use this command like this:

$./mongod --dbpath /Users/username/Documents/OneDrive/nightschool/fos/mongodb/db

To run mongo shell type:

$./mongo

Postman is a Chrome app to send HTTP request for test purpose, you can google Postman and install on your Chrome.
Then I use postman to send a post request to:

http://localhost:8080/api/register

这里写图片描述
To confirm we have insert data into the data base, use mongo shell commands to see documents in collection, type the following into mango shell:
See databases

$show dbs  

To select our database

$use Server

To see collections (or talbes for SQL Database):

$show collections

To query documents in collection:

db.collection.find()

In our case, type:

db.accounts.find()

这里写图片描述

Now we have correctly connet a Node.js server to MongoDB.

I have upload the source code on Baidu for download
Download from Github

Have Fun~~

Reproduced in Strings@Farbox.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值