How it works...

When we call client.connect, we pass in a URI with the mongodb:// protocol as the first parameter. The mongodb module will parse this string and attempt to connect to the specified quotes database. MongoDB will intelligently create this database if it doesn't exist, so unlike MySQL, we don't have to plaster over awkward errors.

Once the connection is made, our ready callback function is executed where we can interact with the database via the db parameter.

We start off by grabbing our quotes collection using db.collection. A collection is similar to an SQL table that holds all our database fields. However, rather than the field values being grouped by columns, a collection contains multiple documents (such as records) where each field holds both the field name and its value (the documents are very much like JavaScript objects).

If both quote and author have been passed as arguments, we invoke the collection.insert method, passing in an object as our document.

Finally, we use collection.find, which is comparable to the SELECT SQL command, passing in an object that specifies the author field and its desired value. The mongodb driver module provides a convenience method (each) that can be called on the result of the collection.find method. The each method executes the iterator function passed to it for each document as and when it's found. The doc parameter is set to null for the last call of the iterator function, signalling that MongoDB has returned all the records.

So we check if doc is falsy (it should always be an object or null, but just in case, checking for !doc means we cover false and undefined as well), and then call db.close, returning early from the function. If doc isn't falsy, we proceed to log out the author and quote.

The second and final db.close call situated at the end of the ready function is invoked only when there are no arguments defined via the command line.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.161.225