diff --git a/Databases/MongoDB/Introduction.md b/Databases/MongoDB/Introduction.md index 747e8d3..535627a 100644 --- a/Databases/MongoDB/Introduction.md +++ b/Databases/MongoDB/Introduction.md @@ -56,6 +56,8 @@ rm /tmp/mongodb-27017.sock Although Mongo is not a relational database it has a structure that we can understand in relation to that paradigm. A **database** is obviously the overall structure. It comprises **collections** which are organised sets of data that are analagous to [tables](/Databases/Relational_database_architecture.md#table) in RDBs. Within each collection are a series of **documents** which we can think of as being equivalent to [rows](/Databases/Relational_database_architecture.md) in RDB table: units that comprise the collection. +A document is a container comprising key-value pairs in the manner of an object. + ## Mongoose ### Connecting to our database @@ -71,4 +73,49 @@ mongoose ``` ### Creating collections and documents -In order start adding collections and documents to our database, we use Mongoose's schema structure. (This is specific to the Mongoose wrapper and is not a structure that is a part of Mongo in general.) \ No newline at end of file +In order start adding collections and documents to our database, we use Mongoose's schema structure. (This is specific to the Mongoose wrapper and is not a structure that is a part of Mongo in general.) + +We use a schema to define the shape of documents in a MongoDB collection. To do this we instantiate an instance of the Mongoose `Schema` class and set our properties: + +#### Creating a schema + +```js +const courseSchema = new mongoose.Schema({ + name: String, + author: String, + tags: [String], + data: {type: Date, default: Date.now}, // if unspecified, entry will default to current date + isPublished: boolean +}); + +``` +This is just like defining an interace or type within TypeScript. +#### Available data types + +The following data types are available: +* `String` +* `Number` +* `Boolean` +* `Array` +* `Date` +* `Buffer` +* `ObjectID` (for UUIDs) + +#### Models + +Once we have established our schema we can then create a **model** of it. A model is basically a class representation of the interface we define in the schema: + +```js +const Course = mongoose.model("Course", courseSchema); +``` +With this in place, we can then create instances of the model. This stands in relation to the model as an object does to a class: + +```js +const course = new Course({ + name: "Node.js Course", + author: "Ozzy Osbourne", + tags: ["node", "backend"], +}); +``` + +// TODO: diagram schema - model - object \ No newline at end of file