Node.js, Express, and Middleware
Basically middleware is anything put between one layer of software and another, something… in the middle. With Node.js, you can easily use express to put middleware between routes, meaning between the HTTP request and the route. Commonly used for things like authentication, checking to see if the user is authorized to view a page when they request a new route before giving them access. Here is an example. `app.use()` is the middleware, simple to create.
const express = require("express");
const app = express();
///Middlewares, a function that executes when a certain route is hit. Good for authentication etc, can check the user each time they hit a route
app.use("/posts", () => {
console.log("this is a middleware");
});
///ROUTES, responds to a request made to a specific address
app.get("/", (req, res) => {
res.send("Hello!");
});
app.get("/posts", (req, res) => {
res.send("postssaa");
});
Mongoose
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.
Not sure EXACTLY what all that means, but I am somehow using it to connect anyways.
MongoDB is a schema-less NoSQL document database. It means you can store JSON documents in it, and the structure of these documents can vary as it is not enforced like SQL databases. This is one of the advantages of using NoSQL as it speeds up application development and reduces the complexity of deployments.
require("dotenv").config();
const myApiKey = process.env.apiKey;
const myApiSecret = process.env.apiSecret;
//////////////The following also works:
require("dotenv/config");
mongoose.connect(
process.env.DB_CONN,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log("Database connected");
}
);
Express Routes
Most people move the express routing out of the main file, and export the routes from another file into it. Keeps the main entry point smaller and easier to read. A routes folder and posts file setup seems to be the ticket here.
///Posts file
const express = require('express'),
const router = express.Router()
///ROUTES, responds to a request made to a specific address
router.get("/", (req, res) => {
res.send("postssaa");
});
module.exports = router;
//Main index.js or app.js file:
//Import Routes frop posts.js file
const postsRoute = require('./routes/posts')
///Middlewares, a function that
//executes when a certain route is hit.
//Good for authentication etc,
//can check the user each time they hit a route
//This one executes each time
app.use("/posts", postsRoute)
Mongoose Schema
Mongoose is an ODM (Object Data Modeler) for Node. MongoDB is a database for storing, usually in JSON type structure. A collection in MongoDB might be called user, and store JSON type objects with things like the name and birthday for each user. However, each of these is not required for each document (JSON type object) added to the collection user. So each document inside the user collection does not have to have the name property, for example. This is different from databases such as MySQL which requires more ridge database structures, MongoDB is much more flexible.
Because MongoDB does not do so, Mongoose is used to define objects, strongly-typed, and mapped to a MongoDB document.
In mongoose, a schema represents the structure of a particular document, either completely or just a portion of the document. It’s a way to express expected properties and values as well as constraints and indexes
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
//title: String,
title: {
type: String,
required: true
},
description: {
required: true,
},
date: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('Posts', PostSchema)
Mongoose Model
Models are defined by passing a
Schema
instance tomongoose.model
.Models are fancy constructors compiled from
Schema
definitions. An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database.