Preface
After the last article Construction of Economic Foundation Complete, then start coding now!
Project framework
Start HTTP Services
Firstly, the / server/app.js file is established. First, the module needed for service is introduced. The following two methods are introduced to start HTTP service.
-
Using Node.js intrinsic module http
var http = require('http'); http.createServer(function (request, response) { // Send response data "Hello Node.js" response.end('Hello Node.js'); }).listen(8888); // Listen on port 8888 // The terminal prints the following information console.log('Server running at http://127.0.0.1:8888/');
-
Using express framework
This project uses the express framework of node.js to start the HTTP server. express official website There are corresponding simple tutorials, API s and so on, which can be consulted by oneself.const express = require('express'), //Loading express module app = express(); //Start a web server app.get('/',function(req,res){ res.send('Hello Node.js'); }) const server = app.listen(3000,function(){ let port = server.address().port; console.log('app listening at http://%s:%s','localhost',port); });
After saving, the command line enters the folder where the app.js file is located, runs the command node app.js, and then browsers access it. http://localhost:3000 That is, you will see the return of'Hello Node.js'.
MongoDB Visualization Tool Robomongo
For testing convenience, we first need to insert some data into our local MongoDB database. For ease of use, MongoDB also has a graphical management tool similar to mysql navicat, Robomongo 1.0.0, download address: https://robomongo.org/download Download and install.
Open Robomongo, click file - > connect (shortcut ctrl+N) in the upper left corner, and click create in the pop-up box to create the connection.
Enter the connection name and address name. The port defaults to 27017. Addresses and ports are generally unchanged.
So test creates a MongoDB connection with the name.
MongoDB, written in C++ language, is an open source database system based on distributed file storage. There is a big difference between MongoDB and MySQL.
First, we click on the test connection just created on the left, right-click on create database, enter the database name testDb and click create to create.
Left mouse click on the newly created testDb database, create collection (that is, the table table table table in the commonly used database), and click create to create the user collection successfully.
Let's start inserting data into the user collection collection collection: right-click user collection - > insert document
[Picture upload...]
The data structure of documents (data in each row) in MongoDB database is basically the same as that of JSON. All data stored in collections are in BSON format. BSON is a binary storage format similar to JSON, referred to as Binary JSON. Therefore, when we insert data, we only need to input the data we want to insert as JSON format. Click save to save to insert data successfully.
{ userName:'dodo', sex:18, sex:'female', job:'font-end Engineer' }
Film upload in...]
Double-click user collection to see the data we just inserted, and the primary key of MongoDB automatically sets the _id field as the primary key.
Start connecting to the database
Use the native API of MongoDB to create the connection, and enter the following code directly in / server/app.js
var MongoClient = require('mongodb').MongoClient, DB_CONN_STR = 'mongodb://localhost:27017/testDb'; # database is testDb var selectData = function(db, callback) { //Connect to user table var collection = db.collection('user'); //Query data var whereStr = {"userName":'dodo'}; collection.find(whereStr).toArray(function(err, result) { if(err) { console.log('Error:'+ err); return; } callback(result); }); } MongoClient.connect(DB_CONN_STR, function(err, db) { console.log("Connect successfully!"); selectData(db, function(result) { console.log(result); db.close(); }); });
This project uses Mongoose to cooperate with MongoDB to operate database
mongoose is an object model tool of mongoDB. It is a node JS driver of mongoDB based on node-mongodb-native, which can be executed in an asynchronous environment. At the same time, it is also an object model library for mongoDB operation, encapsulating some common methods such as mongoDB adding, deleting, modifying and searching documents, making it easier for node JS to operate mongoDB database.
// Loading required modules const mongoose = require('mongoose'); mongoose.Promise = require('bluebird'); const Schema = mongoose.Schema; const UserSchema = new mongoose.Schema({ username: String,//User name sex: String,// Gender age: Number, // Age },{collection:'user'}) // Note that there must be collection here, otherwise mongoose will add suffixes s to user when it comes to the following model. const Models = { User : mongoose.model('user', UserSchema) }; /** * Create database name and connect * Connecting to Mongod instance. */ const dbHost = 'mongodb://localhost/testDb'; mongoose.connect(dbHost); const db = mongoose.connection; db.on('error', function () { console.log('Database connection error.'); }); db.once('open', function () { console.log('The Database has connected.') }); module.exports = Models;