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® 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 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 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 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 is Node’s package manager that will bring in all the packages we defined in package.json.
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
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.
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.
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:

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.