Video Transcript (English)
Hello! In this video, you’ll learn how BSON documents are expressed in Node.js.
You’ll also learn how to define a document by using Node.js.
Binary JSON, or BSON, is the data format that MongoDB uses to organize and store data.
BSON is optimized for storage, retrieval, and transmission across the wire. BSON is more secure than plain text JSON, which is vulnerable to JSON injection attacks. BSON also supports more data types than JSON.
The MongoDB Node.js driver allows us to represent BSON documents as JavaScript objects.
Documents are the foundational organizing principle of storing data in MongoDB because they provide flexible and concise data representation.
Let's examine a typical BSON document to understand how documents are represented in Node.js.
We’ll work with a BSON document from the accounts collection in the bank database. Let’s take a look.
The _id field is a unique identifier for a document in a collection. If we don’t provide it, MongoDB will create one for us. You can think of the _id field as being equivalent to a primary key.
This document contains a sub-document within the address field. This sub-document is also referred to as an embedded document.
Notice that the balance field is represented as a string, which is not recommended. It’s a best practice to model values by using the correct data type. To fix this, we’ll update the document’s “balance” field so that it’s stored as a number, which is the correct data type.
To create the equivalent account document in Node.js, we must instantiate a new JavaScript object and set its primary key, which is the _id.
Node.js objects are essentially the same format as a JSON object or a BSON document. Therefore, we don’t need to change the formatting much, except for using constructors for the ObjectId() instead of the prefixed keys (like $oid) that are used in BSON documents.
Then, we assign the document as the value of a variable. In this example, we’ve assigned the document to the account variable.
Now the document is ready to be sent to the MongoDB server.
Well done!
In this video, you learned what BSON is, why MongoDB uses the BSON data format, and how BSON documents are represented in Node.js.
Remember that it’s recommended that you always use the correct data types for your field values.
Now that you’re done with this lesson, check out the MongoDB documentation on BSON to get a deeper understanding of how and why it’s used.