Mongo DB And Promises
Setting up MongoDB
Note: These instructions are for Windows only.
Download and unzip
.zip
file of MongoDB Community Server. This folder contains all the executables you need to run MongoDB.Create a folder to store your MongoDB data (e.g.
mongodb-data
).Run
mongod.exe --dbpath=path/to/mongodb-data
to start your server. This file is in thebin
folder.Note: You should see the default port
27017
. You can connect to your database server via that port.
Bonus: Do the following to set up a MongoDB database GUI viewer:
Download Robo 3T.
While database server is still running, connect to your server at
localhost:27017
. That's it!
MongoDB inside Node.js
MongoDB provides a native driver npm module to connect to your MongoDB database and perform CRUD operations. Simply npm install mongodb
.
Connecting to MongoDB
With your database server still up, write the following code to connect to MongoDB in Node.js:
Creating documents
This is the create in CRUD. The below code snippet demonstrates how to use insertOne
and insertMany
methods.
insertOne
and insertMany
both take a callback function that gets invoked upon completion of the write operation. If something went wrong, you get an error
object. Otherwise, you get a result
object.
Pro tip: result.ops
is the most useful property in result
. It provides you with an array of all the documents you just wrote with their automatically generated unique IDs.
Object IDs
Any time you create a document, it's automatically assigned an object ID both as a key and a field within the document. These are alphanumeric values meant to be globally unique identifiers or GUIDs. (In contrast, SQL usually has incrementing IDs for its tables like 1, 2, 3, 4.)
Benefits of GUIDs:
MongoDB opted for GUIDs because it ensures zero query collision when you spread your database across multiple servers. This allows for smooth scaling.
Because MongoDB's GUIDs are generated via an algorithm, you can locally generate them without needing contact with your database.
Here's the process to create your own object IDs using the mongodb
Node.js library:
Note: The ObjectID
creates an ID composed of a Unix timestamp, a random value, and a counter. Because of the timestamp embedded inside, you can actually get its value to find out when your document was created!
To add your ID to a new document, simply add it as an _id
property in the object:
Note: Object IDs are represented in MongoDB as binary data. It does this because the string representation we see (e.g. 5df51b461217c710848fbb77
) is double the size of the binary version. It's all about space saving. Proof:
Reading documents
This is the read in CRUD. Here are code snippets for the find
and findOne
methods:
Important: When you use find
, MongoDB doesn't assume that you always want all matching documents back. Sometimes you just want 5 of the documents or maybe even the number of documents (without reading their contents). In order to allow for this flexibility, find
returns a cursor pointing to the matching documents, which you then apply methods to:
toArray
gets all the documentslimit
limits the documents retrieved when chained beforetoArray
count
gets the number of documents matching
Updating documents
This is the update in CRUD. Here are the code snippets for the updateOne
and updateMany
methods:
Note: Notice that you can also use the promise structure for MongoDB instead of just a callback!
More about updateOne
and updateMany
:
The first argument provided is the filter parameters and the second is the update operators.
In the promise response, we're interested in
matchedCount
andmodifiedCount
to learn about the status of our update.
Deleting documents
This is the delete in CRUD. Here are the code snippets for the deleteOne
and deleteMany
methods:
Straightforward! It's just like the methods above!
Last updated