Last Sync: 2022-08-09 08:30:04
This commit is contained in:
parent
d2601a8310
commit
2175545f68
1 changed files with 48 additions and 1 deletions
|
@ -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.)
|
||||
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
|
Loading…
Add table
Reference in a new issue