GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — add changes :apple: · SquaredR98/fullstack-javascript@532235e

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • chapter7
    • chapter7.md
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎chapter7/chapter7.md‎

Copy file name to clipboardExpand all lines: chapter7/chapter7.md
+30-76Lines changed: 30 additions & 76 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,6 @@ connection from your Node.js script.
206206
MongoDB on Heroku: MongoLab
207207
==================================================================================================================================
208208

209-
210209
Now that you've made the application that displays "connected" work locally, it's time to slightly modify it and deploy it to the Heroku PaaS (cloud). The database will also be in the cloud. I recommend using the MongoLab add-on, which provides ready-to-use MongoDB instances that integrate well with Heroku apps (<https://elements.heroku.com/addons/mongolab>). MongoLab (or mLab) also has a very convenient browser-based GUI to look up and manipulate the data and collections.
211210

212211
**Note** You might have to provide your credit card information to use MongoLab even if you select the free version. You should not be charged for a free plan, though.
@@ -322,9 +321,9 @@ The result will be something like this:
322321
2019-12-01T12:34:53.271778+00:00 app[web.1]: { name: 'test', options: { autoIndexId: true } } ]
323322
```
324323

325-
So far you have implemented a local `app.js` file (`code/07-db-connect/app.js` or <http://bit.ly/2LhLrZm>). You enhanced it to work in the cloud (`code/07-db-connect-heroku/app.js` or <http://bit.ly/2LgX5Dy>). After you get the `app.js` and the modified `app.js` files working, let's enhance the latest `app.js` file by adding an HTTP server, so the "connected" message will be displayed in
326-
the browser instead of the terminal window. To do so, we'll wrap the
327-
server object instantiation in a database connection callback. The final implementation is in the file `code/07-db-server/app.js` or at the book's GitHub repository: <http://bit.ly/2LcTd6K>.
324+
So far you have implemented a local `app.js` file (`code/07-db-connect/app.js` or <http://bit.ly/2LhLrZm>). You enhanced it to work in the cloud (`code/07-db-connect-heroku/app.js` or <http://bit.ly/2LgX5Dy>). You learned how to build Node.js programs which work with MongoDB. Great work!
325+
326+
Let's enhance the latest `app.js` file by adding an HTTP server. After you get the `app.js` and the modified `app.js` files working, you modify the `app.js` to add a server so that the "connected" message will be displayed in the browser instead of the terminal window. To do so, we'll wrap the server object instantiation in a database connection callback. The final implementation is in the file `code/07-db-server/app.js` or at the book's GitHub repository: <http://bit.ly/2LcTd6K>.
328327

329328
Supplemental video which walks you through the implementation and
330329
demonstrates the project: <http://bit.ly/1Qnrmwr>.
@@ -356,29 +355,16 @@ client.connect(dbConnUrl, {}, function(error, db) {
356355
})
357356
```
358357

359-
The final Heroku-deployment-ready project is located at
360-
https://github.com/azat-co/fullstack-javascript/tree/master/code/07-db-serverunder.
358+
After the deployment you should be able to open the URL provided by Heroku and see the list of collections. If it's a newly created app with an empty database, there would be no collections. You can create a collection using the MongoLab web interface in Heroku, then check in your app. You can use Mongo shell to connect to mLab too, e.g.,
361359

362-
After the deployment you should be able to open the URL provided by
363-
Heroku and see the list of collections. If it's a newly created app with
364-
an empty database, there would be no collections. You can create a
365-
collection using the MongoLab web interface in Heroku.
366-
367-
For more information on the native MongoDB driver, check out
368-
http://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html
360+
```
361+
mongo --username alice --password dolphin --host mongodb0.herokuserverapp.com --port 28015
362+
```
369363

370364
Message Board: MongoDB Version
371365
==============================
372366

373-
<span id="board" class="anchor"></span>Supplemental video which walks
374-
you through the implementation and demonstrates the project:
375-
http://bit.ly/1QnsfoE.
376-
377-
We should have everything set up for writing the Node.js application
378-
that will work both locally and on Heroku. The source code is available
379-
at
380-
<https://github.com/azat-co/fullstack-javascript/tree/master/code/07-board-api-mongo>.
381-
The structure of the application is simple:
367+
We should have everything set up for writing the Node.js application that will work both locally and on Heroku. The source code is available in the folder `code/07-board-api-mongo` and at <http://bit.ly/2LbCtfX>. The structure of the application is as simple as:
382368

383369
```
384370
/07-board-api-mongo
@@ -400,12 +386,9 @@ Then put out a magic string to connect to MongoDB:
400386

401387
`const uri = process.env.MONGOLAB_URI || 'mongodb://@127.0.0.1:27017/messages'`
402388

403-
Note: The URI/URL format contains the optional database name in which
404-
our collection will be stored. Feel free to change it to something else:
405-
for example, 'rpjs' or 'test'.
389+
**Note** The URI/URL format contains the optional database name in which our collection will be stored. Feel free to change it to something else: for example, `rpjs` or `test`.
406390

407-
We put all the logic inside of an open connection in the form of a
408-
callback function:
391+
We put all the logic inside of an open connection in the form of a callback function:
409392

410393
```js
411394
client.connect(uri, (error, db) => {
@@ -414,11 +397,11 @@ client.connect(uri, (error, db) => {
414397
415398
We are getting the collection with the next statement:
416399
417-
`const collection = db.collection('messages')`
400+
```js
401+
const collection = db.collection('messages')
402+
```
418403
419-
Now we can instantiate the server and set up logic to process our
420-
endpoints/routes. We need to fetch the documents on GET
421-
`/messages/list.json`:
404+
Now we can instantiate the server and set up logic to process our endpoints/routes. We need to fetch the documents on GET `/messages.json`:
422405
423406
```js
424407
const app = http.createServer((request, response) => {
@@ -430,11 +413,11 @@ endpoints/routes. We need to fetch the documents on GET
430413
})
431414
```
432415
433-
On the POST `/messages.json`, we inserting the document:
416+
On the POST `/messages.json`, we insert the document:
434417
435418
```js
436419
} else if (request.method === 'POST' && request.url === '/messages.json') {
437-
request.on('data', function(data) {
420+
request.on('data', (data) => {
438421
collection.insert(querystring.parse(data.toString('utf-8')), {safe:true}, function (error, obj) {
439422
if (error) throw error
440423
response.end(JSON.stringify(obj))
@@ -443,10 +426,7 @@ On the POST `/messages.json`, we inserting the document:
443426
} else {
444427
```
445428
446-
This will be shown in the event that the client request is not matching
447-
any of the conditions above. This is a good reminder for us when we try
448-
to go to the http://localhost:1337 instead of
449-
<http://localhost:1337/messages.json>:
429+
This will be shown in the event that the client request does not match any of the conditions above. This is a good reminder for us when we try to go to <http://localhost:1337> instead of <http://localhost:1337/messages.json> and there are no messages:
450430
451431
```js
452432
response.end('Supported endpoints: \n/messages.json\n/messages.json')
@@ -457,55 +437,38 @@ to go to the http://localhost:1337 instead of
457437
})
458438
```
459439

460-
Note: We don't have to use additional words after the collection/entity
461-
name; that is, instead of `/messages.json` it's perfectly fine to have just `/messages` for
462-
all the HTTP methods such as GET, POST, PUT, DELETE. The main reason why many developers and I use `.json` is to be explicit with the format which needs to be returned back. If you change them in your application code make sure to use the updated CURL commands and
463-
front-end code.
440+
**Note** We don't have to use additional words after the collection/entity name; that is, instead of `/messages.json` it's perfectly fine to have just `/messages` for all the HTTP methods such as GET, POST, PUT, and DELETE. The main reason why many developers and I use `.json` is to be explicit with the format that needs to be returned back. Another way to be explicit is to use `Accept` header set to `application/json`. If you change the endpoints to just `/messages` in your Node.js application code, make sure you update URLs in the provided CURL commands and the supplied Message Board front-end code.
464441

465442
To test via CURL terminal commands run:
466443

467444
`$ curl http://localhost:5000/messages.json`
468445

469446
Or open your browser at the <http://locahost:1337/messages.json> location.
470447

471-
It should give you an empty array: `[]`, which is fine. Then POST a
472-
new message:
448+
It should give you an empty array (`[]`), which is fine. Then POST a new message:
473449

474450
`$ curl -d "username=BOB&message=test" http://localhost:5000/messages.json`
475451

476-
Now we must see a response containing an ObjectID of a newly created
477-
element, for example:
452+
Now we must see a response containing an ObjectID of a newly created element, for example:
478453

479454
```
480455
[{"username":"BOB","message":"test","_id":"51edcad45862430000000001"}]
481456
```
482457

483-
Your ObjectId will be different. :-)
458+
Your `ObjectId` will be different. :-)
484459

485460
If everything works as it should locally, try to deploy it to Heroku.
486461

487-
To test the application on Heroku, you could use the same
488-
[CURL](http://curl.haxx.se/docs/manpage.html) commands
489-
(http://curl.haxx.se/docs/manpage.html), substituting http://localhost
490-
or "http://127.0.0.1" with your unique Heroku app's host/URL:
462+
To test the application on Heroku, you could use the same [CURL](https://curl.haxx.se/docs/manpage.html) commands (https://curl.haxx.se/docs/manpage.html), substituting <http://localhost> or <http://127.0.0.1> with your unique Heroku app's host/URL:
491463

492464
```
493465
$ curl http://your-app-name.herokuapp.com/messages.json
494-
$ curl -d "username=BOB&message=test"
495-
http://your-app-name.herokuapp.com/messages.json
466+
$ curl -d "username=BOB&message=test" http://your-app-name.herokuapp.com/messages.json
496467
```
497468

498-
It's also nice to double check the database either via Mongo shell:
499-
`$ mongo` terminal command and then `use twitter-clone` and
500-
`db.messages.find()`; or via MongoHub
501-
(<https://github.com/bububa/MongoHub-Mac>), mongoui
502-
(<https://github.com/azat-co/mongoui>),
503-
mongo-express (<https://github.com/andzdroid/mongo-express>) or in case of
504-
MongoLab through its web interface accessible at the heroku.com web
505-
site.
469+
It's also nice to double check the database either via Mongo shell: `$ mongo` terminal command and then `use twitter-clone` and `db.messages.find()`; or via Compass (<http://bit.ly/2Lft3Qs>), my tool `mongoui` (<https://github.com/azat-co/mongoui>), `mongo-express` (<https://npmjs.org/mongo-express>) or in case of MongoLab through its web interface accessible at the Heroku website.
506470

507-
If you would like to use another domain name instead of
508-
http://your-app-name.herokuapp.com, you'll need to do two things:
471+
If you would like to use another domain name instead of http://your-app-name.herokuapp.com, you'll need to do two things:
509472

510473
1. Tell Heroku your domain name:
511474

@@ -514,22 +477,13 @@ http://your-app-name.herokuapp.com, you'll need to do two things:
514477
2. Add the CNAME DNS record in your DNS manager to point
515478
to http://your-app-name.herokuapp.com.
516479

517-
More information on custom domains can be found at
518-
[devcenter.heroku.com/articles/custom-domains](https://devcenter.heroku.com/articles/custom-domains)
480+
Custom domains will hide the fact that your application is hosted on Heroku. For more information on custom domains can be found at <https://devcenter.heroku.com/articles/custom-domains>.
519481

520-
Tip: For more productive and efficient development we should automate as
521-
much as possible; that is, use tests instead of CURL commands. There is
522-
an article on the Mocha library in the BONUS chapter that, along with
523-
the `superagent` or `request` libraries, is a timesaver for such tasks.
482+
**Tip** For more productive and efficient development we should automate as
483+
much as possible; that is, use tests instead of CURL commands Use HTTP libraries such as `axios`, `superagent` or `request` to test your REST APIs. They are a timesaver for such tasks. There is
484+
a chapter on the Mocha library and Node.js testing in my other best-selling book *Practical Node.js, 2nd Edition* (Apress, 2018): <http://bit.ly/2LdCNL3> and <https://github.com/azat-co/practicalnode>.
524485

525486
Summary
526487
=======
527488

528-
In this chapter we've covered the MongoDB database and its shell.
529-
MongoDB uses an extended version of JSON, which is called BSON. Then we
530-
switched to Node.js with the native MongoDB driver. Many other MongoDB
531-
Node.js libraries depend on the native driver and build on top of it.
532-
For this reason, it's good to know it. To use MongoDB on Heroku, we
533-
utilized MongoLab add-on (the magical `MONGOLAB_URI`). Finally, we use
534-
the acquired knowledge to add persistence to the Message Boards
535-
application.
489+
In this chapter we covered the MongoDB database and its shell. MongoDB uses an extended version of JSON, which is called BSON. Then we switched to Node.js with the native MongoDB driver. Many other MongoDB Node.js libraries depend on the native driver and build on top of it. For this reason, it's good to know it. To use MongoDB on Heroku, we utilized the MongoLab add-on (the magical `MONGOLAB_URI`). Finally, we used the acquired knowledge to add database store (persistence) to the Message Boards application.

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.