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()
  })
})

No comments:

Post a Comment