TIL030_210428

JIYOON·2021년 4월 28일
0

TIL

목록 보기
30/42
post-thumbnail

🍊 감상

어려운 부분 공부할 때 집중 안 하려는 안 좋은 버릇 고치기

📙 열품타 코딩 시간 9hour
👍🏼 -
👎🏼 -

🚀 목표

  • Udemy에서 Javascript 강좌 수강하기 (424/682)
  • 개인 프로젝트 진행

📣 The Web Developer Bootcamp 2021

35. Defining RESTful Routes

patch request : suppoesd to be used when we are patching a resource either updating or adding on som thing to an existing resource.
Payload only contains that patch.

put request : Payload includes a whole comment - not just the text, but also the id, also the user name. We just replace what was already there in our database with the new payload.

const path = require('path');
//node.js의 path 모듈로 운영체제별로 경로 구분자가 달라 생기는 문제를 해결한다
//폴더와 파일의 경로를 쉽게 조작할 수 있다
const methodOverride = require('method-override');
//RESTful API의 7가지 패턴 중 put(업데이트),delete(삭제)는 html이 지원하지 않는다
//app.post를 대신 사용할 수 있으나 RESTful 패턴에 부합하기 위해 method-override 패키지 사용
const { v4: uuid } = require('uuid');
//universally unique identifier 고유한 아이디 생성하는 라이브러리
//v4는 랜덤값을 기반으로 생성하는 것

미들웨어

응용 소프트웨어가 운영체제로부터 제공받는 서비스 이외에 추가적으로 이용할 수 있는 서비스를 제공하는 컴퓨터 소프트웨어. 다른 기종간 플랫폼을 연결하여 데이터를 주고받을 수 있도록 중간에서 매개역할을 하는 소프트웨어.

참고링크: 길벗시나공 IT

프레임워크

개발을 하는 데 있어 표준을 제공해주고 다른 여러 서비스들을 통합, 편리하게 제공해주는 환경

Express

라우팅, 정적파일 호스팅 관리, 템플릿 엔진, 보안, 세션 등의 api를 제공, node.js 상에서 동작하는 웹 개발 프레임워크로서 node.js의 미들웨어 기능을 한다.

참고링크: 꿈꾸는 개발자

Routing

라우팅은 하나의 접속에 따른 여러 개의 망으로 분리해주는 기능, 기본 접속 index.js로 들어온 뒤 해당 파일에서 각 url 별로 분기를 태워 서비스를 수행한다.

static file

js, css, image, font 등과 같이 개발자가 사전에 미리 서버에 저장해둔 파일들을 말한다.

const express = require('express');
//require로 모듈을 불러온다
const app = express();
//express()를 호출하여 미들웨어 셋팅을 한다

parsing

가지고 있는 데이터를 내가 원하는 형태의 데이터로 가공하는 과정
이러한 과정을 수행하는 모듈 혹은 메소드를 parser이라고 한다.

app.use(express.urlencoded({ extended: true }));
//미들웨어 없이 req.body에 접근할 경우 디폴트값이 undefined로 설정돼있다
//request body에서 post request한 데이터를 파싱하기 위한 것
app.use(express.json());
//req.body에서 post한 json데이터를 파싱하기 위한 것
app.use(methodOverride('_method'));
//html이 지원하지 않는 put,patch,delete request를 사용하기 위한 것
app.set('views', path.join(__dirname, 'views'));
//views는 사용하는 템플릿 엔진이 있는 디렉토리이다.
//뷰 페이지의 폴더 기본 경로로 directoryname+views로 하겠다는 것, 절대적 위치 설정
//join all arguments together and normalize the resulting path
app.set('view engine', 'ejs');
//템플릿 엔진 설정을 ejs로 한다, 
//ejs는 정적인 html을 템플릿을 활용해 동적으로 만든다, html의 태그처럼 js 삽입 가능
app.listen(3333, () => {
  console.log('on port 3333');
});
//listen()로 오픈할 포트를 정의한다.
//서버의 상태가 listen이기에 다른 접속으로부터 대기 상태가 된다
//index - renders multiple tweets
app.get('/tweets', (req, res) => {
  res.render('tweets/index', { tweets });
});
//new - render a form
app.get('/tweets/new', (req, res) => {
  res.render('tweets/new');
});
//create - creats a new tweet
//const username = req.body.username;
app.post('/tweets', (req, res) => {
  const { username, tweet } = req.body;
  comments.push({ username, tweet, id: uuid() });
  res.redirect('/tweets');
});
//show - details about one particular tweet
app.get('/tweets/:id', (req, res) => {
  const { id } = req.params;
  const tweet = tweets.find((t) => t.id === id);
  res.render('twwets/show', { tweet });
});
//eidt - renders a form to edit a tweet
app.get('/tweets/:id/edit', (req, res) => {
  const { id } = req.params;
  const tweet = tweets.find((t) => t.id === id);
  res.render('tweets/edit', { tweet });
});
//update - updates particular tweet
app.patch('/tweets/:id', (req, res) => {
  const { id } = req.params;
  const foundTweet = tweets.find((t) => t.id === id);
  const newTweetText = req.body.tweet;
  foundTweet.tweet = newTweetText;
  res.redirect('/tweets');
});
//delete/destroy - removes a single tweet
app.delete('/tweets/:id', (req, res) => {
  const { id } = req.params;
  tweets = tweets.filter((t) => t.id !== id);
  res.redirect('/tweets');
});

36. Our first database : MongoDB

365. Introduction to database

why use a database instead of saving to a file

Database can handle large amount of data efficiently and store it compactly.
They provide tools for easy insertion, querying(파일의 내용을 알아내는 것, 검색, 명령을 요청해서 원하는 정보를 추출하는 것, sort, filter), and updating of data.
They generally offer security features and control over access to data.
They generally scale well.

366. SQL vs NoSQL Databases

SQL database

structured query language database are relational databases. We pre-define a schema(데이터베이스의 구조와 제약 조건에 관한 전반적인 명세를 기술한 메타데이터의 집합, 개체, 속성, 관계 및 제약 조건에 대해 전반적으로 정의한다) of tables before we insert anything. (관계형 데이터베이스)

No-SQL database

NoSQL databases do not use SQL. There are many types of no-sql databases, including document, key-value, and graph stores.

-> more flexibility and freedom

참고링크: 귀여운 쫑이

367. Why we're learning mongo

  1. Mongo is very commonly used with Node and Express (MEAN & MERN stacks)
  2. It's easy to get started with
  3. It plays particularly well with javascript

MEAN: MongoDB, Express, Angular, Node
MERN: MongoDB, Express, React, Node
LAMP: 리눅스, 아파치, MySQL, PHP.

-> MySQL 배워보도록 (sql database)

참고링크: mongodb

370. The mongo shell

mongo
show dbs (데이터 안 들어간 데이터베이스 안 보임)
use animalShelter (create db)
db (데이터 안 들어간 데이터베이스도 보임)

371. What on earth is BSON

bson(binary json) is more compact that json

372. Inserting with mongo

collection : grouping of data in database. (container of similar data)

use animalShelter (create db and go into db)
db.dogs.insertOne({name: "charile", age:3, breed:"corgi", catFriendly: true})
// dogs는 collection
// insertOne 이나 insertMany보다는 insert를 자주 쓴다
// {} 오브젝트 안은 json 형태로 안 적고 javascript 형태로 적어도 알아서 bson으로 바꿔줄 것
show collections
db.dogs.find() //콜렉션 안 모두 보여줌
_id: mongo에서 자동으로 만들어주는 것, primary key, 콜렉션 안에서 유일함

373. Finding with Mongo

db.dogs.find({breed:"corgi"})
db.dogs.find({catFrienly:true, age:17})
// instead of returning all of them together in some collection at once, this returns a cursor that we can then iterate over or we can just print it out.
// find() returns the cursor of refernce to the results.
db.cats.find() = db.cats.find({})

374. Updating with Mongo

db.dogs.updateOne({name: 'Charlie'}, {$set: {age:4, breed:'Lab'}})
-> first argument: selector
-> second argument: key-value to update

db.dogs.updateMany({catFriendly:true},{$set: {isAvailable:false}})
-> 없으면 추가됨

db.cats.updateOne({age:6}, {$set:{age:7}, $currentDate:{lastChanged:true}})

375. Deleting with Mongo

db.cats.deleteOne({name: 'Blue'})
db.dogs.deleteMany({isAvailable:false})
db.dogs.deleteMany({}) -> delete entire collection

crud: create, read, update, delete

376. Additional Mongo operators

{name:'Rusty', personality:{catFriendly: true, childFriendly: true}}
property childFriendly is nested inside of personality
->db.dogs.find({childFriendly:true}) 이건 틀린 문법
->db.dogs.find({'personality.childFriendly':true})

gt greater than db.dogs.find({age: {gt: 8}})
gt greater than or equal to db.dogs.find({age: {gt: 8}})
$lt less than

in : breed가 Mutt or Corgi & age is less than 10 db.dogs.find({breed: {in: ['Mutt', 'Corgi']}, age:{$lt: 10}})

ne:notequalne : not equalnin : not in

db.dogs.find(or: {childFriendly:true}, age:{lt: 10}})

37. Connecting to Mongo with Mongoose

378. What is mongoose

ODM

object data mapper or object document mapper
ODMs like mongoose map document coming from a database into usable javascript objects. 객체와 문서를 매칭한다 -> 자바스크립트의 객체인 object와 mongodb의 문서인 document, 문서를 db에서 조회할 때 자바스크립트 객체로 바꿔준다.

Mogoose

Mogoose provide ways for us to model out our application data and define a schema. It offers easy ways to validate data and build complex queries from the comfort of JS.
connects mongo and node

379. Connecting mongoose to mongo

npm i mongoose

공식문서: mongoose

//in index.js
const mongoose = require('mongoose');
mongoose
  .connect('mongodb://localhost:27017/movieApp', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log('connected');
  })
  .catch((err) => {
    console.log('error');
    console.log(err);
  });
//node index.js -> connected

0개의 댓글