3. lab steps
- 3.0.1 code visual studio, Postman, Robot 3T are ready on your mac.
- 3.0.2 have a mongodb ready:
- mongodb is a database name, like mysql, Oracle.
- Use homeBrew to install mongodb, which will be in your mac system area. You will not see the folder.
- Then, allocate storage folder (/data/db) under your mongodb root folder.
- Your mongdb and its storage folder are in the scope of your mac computer. They are not in project scope. You will not see them.
- 3.0.3 have your application ready.
- open code visual studio
- from the finder, drag and drop your cloned application folder into it.
- 3.0.4 make libraries installed.
- from menu view, click integrated terminal to open a window pane with the visual stduio.
- npm install to install the libraires specified in package.json
- 3.1 in the termianl window, enter mongod to start the mongodb server.
- 3.2 add the second terminal window, enter npm start to launch the nodejs web server.
- in package.json file, you'll see the one key-value pair under key script
- "start": "nodemon ./index.js --exec babel-node -e js"
- Command nodemon replaces node. The server can listen and respond any code change.
- It also take care javascript language transpiling, defined in file .babelrc.
- 3.3 Post a document from Postman
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 {}
...
Functions
Users
notes:
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
});
comments:
- 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)
comments:
- 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.
- In mac applications, click Postman to open it.
- go to My Workspace
- selectPOST, enter localhost:3000/contact
- selectbody, and select x-www-form-urlencoded
- Based on the data model, enter key-value pairs
- click button send
- 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.
- 3.4 Using Robo 3T to verify
- in the popup Mongodb Connections dialog, click Connect
- Under node Mongodb, you see database CRMdbis created.
- Under it, there are three nodes - Collections, Functions, Users
- Under Collections, you see contacts is created.
- right-click contacts, select view docuemnts
- You can see the document.
5. javascript code partition
// to begin with package.json
"main": "index.js", // the entry point
//overall folder and file structure
| application folder
- index.js
|src
|controllers
- crmController.js
|models
- crmModel.js
|routes
- 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
...
app.listen(...)
// 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.send(err)
}
res.json(contact) // just for test purpose
});
};