mongod is a database server
A databases is a collection of data organized in a way that is easy to get information
A query is asking questions about data or executing comamnds to operate on the stored data
Software that provides a way to store/retrieve data In charge of creating databases (can have more than one database in it) Normally run as a server Handles memory, security, etc.
In any software you build, there are multiple moving parts.
Client (front-end) <-> API (back-end) <-> DB server (for persistent data storage)
NoSQL (Not Only SQL): a type of database
Document databases store information as a document.
How data is going to be stored
Student question: Is Mongo safer to store data? SQL: Structured Query Language
SQL-injection: Vulnerability to the access of data Some systems that access SQL use strings and are vulnerable to attacks
Answer:
MongoDB
mLab (used to be Mongo Lab) Advantage:
Don't download local instance, you connect to their service and they store your data. Offers 500mb tier for free
127.0.0.1 - IP address to local host
If there are no documents in a database, the database does not show up in show dbs
REPL - read evaluate print loop
Response you get from insert (nInserted) is the number of things inserted
Every document inserted into a collection wil be given an ID unless one is provided.
Client <-JSON-> [API (driver)] <-BSON-> [DB-Server] The driver translates the language of the client to something the database understands
('mongodb://server:port/databaseName')
mongoose.connect('mongodb://localhost/beardb')
If yarn start does not work, try deleting Yarn Lock, yarn, yarn start
Reason you create schema: compile into model
{ species: String }
<- shorthand syntax (when only one property)
species: {
type: String,
required: true
}
^ longer form
const schemaName = mongoose.Schema(definition, options)
Definition example:
const definition = {
type: String,
required: true,
unique: true,
},
latinName: {
type: String,
require: true
},
createdOn: {
type: Date,
default: Date.now()
}
});
Options example:
const options = { timestamps: true }
- this will create createdAt and modifiedOn fields in addition to fields specified in the schema
const schemaName = new mongoose.Schema(definition, options)
const \_\_\_\_model = mongoose.model('ModelName', schemaName, 'collectionName')
By default, mongoose will take the name of the model, lowercase it, pluralize it, and that will be the name of the collection in the database. If you have an existing collection name that might conflict, you might want to set the third argument to a specific collection name.
router.route('/').get(get).post(post)
function get (req, res) {
res.status(200).json({ route: '/api/bears' })
}
function post (req, res) {
const bearDate = req.body
const bear = new Bear(bearData)
bear
.save()
.then(bear => {
res.status(201).json(bear)
})
.catch(err => {
res.status(500).json(err)
})
}