Thursday, December 22, 2016

Learnyoumongo Exercise 3 solution and explanations


var mongoDatabaseBeingUsed = require('mongodb').MongoClient  // MongoClient is a set of functions that allow your code to connect to the mongo database. Without something like MongoClient, your code would have no way of reading or writing to the database

var threshold = parseInt(process.argv[2])  // Why is parseInt getting used here? Because one of the things it does is take a string and change it to an integer. You are going to need this variable to be in integer form later on


var url = 'mongodb://localhost:27017/learnyoumongo'  // 'The database' // 'is being listened to here' // 'and this is the resource from it we want'

mongoDatabaseBeingUsed.connect(url, function(err, db) { // 'Here, handle an error or handle the db'
  if (err) throw err
  var parrots = db.collection('parrots') // OK, here we actually get into what a mongo database is and how a mongo database works. It's kind of like mongo keeps all its information on a grocery list, (whereas something like SQL keeps all of its information on something that looks like an Excel spreadsheet). That mongo document is called a BSON and looks and acts kind of like a list of JSONs (if you have made it this far in FCC, you are familiar with JSON at this point). So picture a list  of JSONs on a piece of paper. Each individual JSON in mongo is called a 'collection.' The piece of paper containing the list of JSON-like entries is the mongo database. SO, "var parrots = db.collection('parrots')" means 'get me the collection called "parrots" from the database we are already connected to, and make the variable called "parrots" point to it.'


  parrots.find({     age: {       $gt: threshold     }   }).toArray(function(err, docs) {
// Arright, a couple of things to wrap your head around with the above statement. First of all, we don't want to end up with a variable containing a bunch of values. We want a pointer pointing to a certain section of the mongo db. This pointer is called a 'cursor' in mongo-speak.   Now, .find() points cursors at what we need the cursors pointed at, and whatever that cursor is pointing at, we want to then populate an array with so we can print it with console.log. So, that is why we are using the collection.find().toArray() convention here.


    if (err) throw err
    console.log(docs)
)
    db.close()
  })
})

Wednesday, December 21, 2016

Learnyoumongo (Mongo in C9) exercise 2 and 3 pitfalls for beginners

Sorry, no explicit solution here - I am writing for those who just need to get off the ground and are trying to understand exactly what is required of them for this tutorial.

It is important to realize that exercises one and two are not just their own exercises but the necessary steps leading up to getting everything running properly before you can even run your solution for exercise 3.

It took me a while to realize this (duh), so let me repeat the above information: Exercises one and two of the learnyoumongo tutorial get you connected and get the server running in the background. So you can't do exercise one day, two the next, then come back in a couple days, write your solution for three and expect it to run. After you have put together your solution for exercise three, you have to go back and repeat exercises one and two as the first steps of exercise three.

Before you do exercise 3:

1. Start a new terminal and enter the command $ learnyoumongo
2. Select exercise 1 and hit enter
3. If you have already done exercise one before, this time just enter $ learnyoumongo verify and hit enter
4. Enter the command $ learnyoumongo
5. Select exercise 2 and hit enter
6. When the directions say "To start mongo on port 27017, run mongod --port 27017 --dbpath=./data" don't do that. Do this:

    $ mongod --port 27017 --dbpath=./data --smallfiles

Otherwise you might get an error that you need to free up space

7. Open a second terminal and DO EVERYTHING ELSE IN THE SECOND TERMINAL, from "$ npm install mongodb" to "$ learnyoumongo verify [solution.js]" for exercise 2 to everything for exercise 3. Do it all in the second terminal with the db server running in the first terminal.

Side note:

If you are messing around trying to get stuff to work and get the "journal" or the "lock" error followed by the message that it failed to connect, do this:

    $ mongod --dbpaths=./data -- repair

...assuming you called your data file "data"

I still have not figured completely why that works, but it worked for me when I encountered CONNECTION errors.

Monday, December 12, 2016

Stylish CSS solution and explanations

var express = require('express')
var app = express();
var stylus = require('stylus') //sylus is yet another CSS preprocessor, written this time for Node
var STATIC_DIR = process.argv[3] // static files hold scripts, css files, etc - here the lesson is sending a request that contains one of these - the goal is convert it to regular CSS


app.use(stylus.middleware(STATIC_DIR))//ok app, I don't want to just write normal ole css, I'm fancy. I want to write stylus 
//instead 'cause it gives me all sorts of cool extra tools to keep my css code nice and tidy. 
app.use(express.static(STATIC_DIR))//I've let you know I want to use stylus, now when you're in the middle of firing up my app, 
//before you consider everything good to go, take a look around, find all my stylus files and convert them into normal css so 
//the browsers can understand them


app.listen(process.argv[2]) //OK to get the ball rolling listen for requests on this port

Friday, December 9, 2016

Param Pam Pam solution and explanations

Directions:
Create an Express.js server that takes a parameter from a browser’s request (in this case, it’s going to take a parameter from the request called ‘id’) and PUT it in a specified endpoint (in this case, PUT '/message/:id').
(So that if ‘id’ is ‘526aa677a8,’ the endpoint ends up like this:   ‘/message/526aa677a8’ )
Then, for your response, return the SHA1 hash of the current date
plus the sent ID (basically, take the current date plus the ID and encrypt all of it!)
Use SHA1 hash to encrypt stuff this way:
                                require('crypto')
                                  .createHash('sha1')
                                 .update(new Date().toDateString() + id)
                                .digest('hex')
Code:
var express = require('express')
var app = express();
app.put('/message/:id', function (req, res) {
                 var id = req.params.id // ‘params’ on the IncomingMessage object is ‘params: { id: '4b693a688d2115d70c6f1d95edac8651' }’
                // if you want to, do this to see the request from the browser:          var test1 = req      console.log(test1)
                 var str = require('crypto'). // Now, add it to the current date and encrypt everything
createHash('sha1').
update(new Date().
toDateString() + id).
digest('hex')
                 res.send(str)  // send the string of encrypted characters back to the client
})
app.listen(process.argv[2]) //OK, to get the ball rolling listen for requests here
OUTPUT:

1d408bcfd164a6c39dc07530c1505c353f103d98’  (yep, a bunch of gobbledygook-  because it’s encrypted!)

What's In A Query solution and explanations

Directions:
Write a route that extracts data from query string in the GET '/search' URL route (e.g. ?results=recent&include_tabs=true) and then outputs it back to the user in JSON format.
Code:
var express = require('express')
var app = express(); // make “app” an instance of express
                 app.get('/search', function (req, res) {  // The ol’ “app.method(path.handler)” format
                 var result = req.query // Use “req.query” on the query string that comes in from the browser, and find out what the parameters of the query are, and return just those
                 res.json(result) // send back the result to the browser in JSON format --- could also have used “res.send(result),” I guess
}) // end of GET statement
app.listen(process.argv[2]) //OK, get the ball rolling by listening for requests here

OUTPUT:
{
"results":"recent",
"type":"quote",
"page":"5"

}

JSON Me solution and explanation

“JSON Me”


Directions:
Write a server that reads a file when it receives a GET request from a webpage, then parse the file’s contents into JSON format, and then output the JSON to the client(the browser).
·         The port is passed in process.argv[2].  The file name is passed in process.argv[3].
·         Respond with:    res.json(object)
·         Everything should match the '/books' resource path.
Code:
var express = require('express')
var fs = require('fs')
var app = express();
app.set('json spaces', 0);  // this was a workaround to prevent a common error
app.get('/books', function (req, res) {  // “When a GET request is made to the home page, do this” (per the directions, everything matches the '/books' resource path)
                         var filename = process.argv[3]  // “Point ‘filename’ to this array” The file name is passed in process.argv[3] per the instructions
                   fs.readFile(filename, function(e, data) { // “Read the file and save it to memory, or return an error
                  if (e) return res.send(500)
                 try {
                 books = JSON.parse(data)  // “take what is read, parse it into JSON, and point ‘books’ at the JSON data
                 } catch (e) {      res.send(500)
                }
                          //res.send(books) 
                       res.json(books) // “this is the response to the page
                  }) //end of readFile
}) //end of GET
app.listen(process.argv[2])  // “OK, to get the ball rolling, listen for requests at this port


OUTPUT:

"[{\"title\":\"Express.js Guide\",\"tags\":[\"node.js\",\"express.js\"],\"url\":\"http://expressjsguide.com\"},{\"title\":\"Rapid Prototyping with JS\",\"tags\":[\"backbone.js\",\"node.js\",\"mongodb\"],\"url\":\"http://rpjs.co\"},{\"title\":\"JavaScript: The Good Parts\",\"tags\":[\"javascript\"]}]"