21. building restful Web APIs with nodejs express, mongoose



           The Mongodb structure is introduced in on example as below:

           CRMdb                           --- database name
                Collections                --- data
                    contacts               --- like a table in a relation table
                        document 1 {}      --- like a row in a relation table
                           many key-value pairs    ---- like columns in a relation table
                        document 2 {}

            1. When you post a document, if the database does not exist, the mongodb 
               will create the database and other entities dynamically.
            2. Mongoose is used to define the structure of a document.
            3. The database name, doucment name, collection name are all from the code.

                code example 1 ----------------------------------------
                mongoose.connect('mongodb://localhost/CRMdb', {
                    useMongoClient: true
                  - The server is the client of the mongodb server.
                  - If using mongodb shell, some mongodb client object is used for connect.
                  - The word mongodb in the url is a network protocal name.

                code example 2  ---------------------------------------
                import {ContactSchema} from '../models/crmModel.js'
                const Contact = mongoose('Contact', ContactSchema)
                - Both the names for the document and the document collection 
                  are from the above code.
                - A separate file is used for defining the document' structure.
                  It is called document model.
        - A http POST request is sent to the route, localhost:3000/contact.
        - Then, the webserver send the document to the mongodb for insert.
        - The db tier sends a response back to the webserver.
        - the webserver sends back a response message to the web clinet, Postman.
        - in the response area of the postman, you see the json data
        - In addition to the data, which you enter previously, there are some more.
        - One example is the key _id,
          The mongodb will create this key-value automatically.
          My experience in cloud is the same.  Both use document database.

       // to begin with package.json
       "main": "index.js",            // the entry point

       //overall folder and file structure
       | application folder
            - index.js
                    - crmController.js
                    - crmModel.js
                    - crmRoutes.js

        //       src/index.js   ----------------------------
        import routes from './src/routes/crmRoutes'
        const app = express()
        mongoose.Promise = global.Promise                           // async for mongoose 
        mongoose.connect('mongodb://localhost/CRMdb', ...)          // connection between the web server and db server
        routes(app)          // app is an express instance

        //       src/routes/crmRoutes.js----------------------
        import { addNewContact } from '../controllers/crmController'     // import a function
                                     // up to folder src, then down folder controllers
        const routes = (app) => {
            app.route('/contact')                                // what is the request for 
            .post(addNewContact)    // method argument is a function for db insert 
        export default routes

        //       src/models/crmModel.js ----------------------
        import mongoose from 'mongoose';
        const Schema = mongoose.Schema;
        export const ContactSchema = new Schema({    //document definition
            firstName: {
                type: String,
                required: 'Enter a first name'
            phone: {
                type: Number
            }, .....

        //       src/controllers/crmController.js   ----------
        import mongoose from 'mongoose'
        import { ContactSchema } from '../models/crmModel'        //import a object

        // Contact is the type of mongoose.Model
        const Contact = mongoose.model('Contact', ContactSchema);

        export const addNewContact = (req, res) => {
            // newContact is a instance of mongoose.Model
            let newContact = new Contact(req.body);     
            // for a post request, the payroll is in req.body
            // the data in the network must also be encoded.
            // the middleware, body-parser, will translate the data in network format to json format.
            // save is mongoose.Model api, db insert
            // other methods like find (note: for all), 
            //    findById(req.params.contactId,..),  findOneAndUpdate, remove
            newContact.save((err, contact) => {
                if (err) {
                res.json(contact)        // just for test purpose

6. mongodb installation