Add Mongoose

1. Install and configure mongoose

2. Setup campground model

3. Use campground model inside of our routes 

 

 

Show pages

1. Review the RESTFful routes we're seen so far

2. Add description to our campground model

3. Show db.collection.drop()

4. Add a show route/templates

 

RESTFUL ROUTES sample

name url verb description
INDEX /dogs GET Display a list of all dog
NEW /dogs/new GET Display  form to make a new dog
CREATE /dogs POST Add new dog to DB
SHOW /dogs/id GET Show info about one dog

 

<app.js>

const express = require("express"),
	app = express(),
	bodyParser = require("body-parser"),
	mongoose = require("mongoose");

// mongodb와 mongoose 연결하여 js로 mongodb 사용 가능하게 설정한다. 27017은 mongodb의 기본 포트
mongoose.connect("mongodb://localhost:27017/yelp_camp", {useNewUrlParser: true, useUnifiedTopology: true});

// bodyParser를 사용할 수 있도록 설정
app.set(bodyParser.urlencoded({extended: true}))

// view engine이란 node js에서 다양한 형태의 language를 사용 시 해당 langauge들을 문제없이 사용할 수 있도록 해준다
// ex) HTML5, JSP etc
app.use("view engine", "js")

// Shcema Setup. DB Schema를 다음과 같이 설정한다. 일종의 템플릿으로 아래의 형태로 key-vale를 가진다. 
// 기본적으로 해당 Schema를 사용할 경우 3개의 key-value pair를 가진다.
const campgroundSchema = new mongoose.Schema({
	name: String,
	image: String,
	description : String
})

// 위에서 선언한 형태의 Schema로 컴파일된 모델의 속성을 가진 Campground을 새로 선언한다.
const Campground = mongoose.model("Campground", campgroundSchema);



// RESTFUL Route를 각각의 목적에 따라 선언한다.
app.get("/campgrounds", (req, res) => {
	//DB에서 campgrounds 데이터를 조건없이({}) 조회(find)한다. 즉 모든 데이터 조회.
		// 조회를 위해 2개의 인자를 사용한다. (err 여부와 db에서 받은 모든 정보)
	Campground.find({}, (err, allCampgrounds) => {
		if(err){// err 발생 시 
			console.log(err); // 터미널에 err를 출력
		} else {	// err 없을 시
			res.render("index", {campgrounds: allCampgrounds}); //index.ejs에 campgrounds라는 이름으로 allCampgrounds를 대입한다.
		}
	})
});


//CREATE - 새로운 campground를 database에 생성 
app.post("/campgrouds", (req, res) => { // POST method가 /campgrounds route로 전달되면 
	const name = req.body.name;	// 요청한 body의 name = name 값을 const name에 할당
	const image = req.body.image; // 요청한 body에 name = image 값을 const image에 할당
	const desc = req.body.description; // 요청한 body에 name = description 값을 const description에 할당
	// 위의 name, image, desc를 하나의 obj에 저장한다. 사용할 형태는 campgroundSchema와 동일하므로 각각 key-vale 형태로 맞춰준다.
	const newCampground = {name: name, image: image, description: desc};

	// DB에 mongoose로 모델링한 새로운 데이터를 생성하고 저장한다.
	Campground.create(newCampground, (err, newlyCreated) => {
		if(err){ // err 발생 시 터미널에 내용 출력
			console.log(err)
		} else {
			res.redirect("/campgrounds"); // 정상 동작 시 "/campgounds"로 페이지를 redirect하여 저장된 값을 페이지에서 볼 수 있도록 한다. 
		}
	})
});


//NEW - 새로운 campground를 생성할 수 있는 form을 보여준다.
app.get("/campgrounds/new", (req, res) => {
	res.render("new.ejs");	// "/campgrouynds/new"로 GET method 요청이 서버로 들어오면 new.ejs를 렌더링 한 값을 클라이언트로 respose한다.
});


//SHOW - 상세페이지를 보여준다. "/campgrounds" 페이지는 현재 DB에 저장된 데이터를 한 페이지에 출력하므로, description을 보여주는 개별 페이지로 이동시킨다.
app.get("/campgrounds/:id", (req, res) => {
	// 주어진 id 값으로 db를 검색하고, 검색한 데이터를 특정 페이지에 출력한다. 
	Campground.findById(req.params.id, (err, foundCampground) =>{ //기본 메소드인 findById를 사용해 campgroundSchema로 모델링한 campground를 id로 조회한다.
		if(err){
			console.log(err)
		} else { // err가 없을 시 렌더링한 show.ejs 응답한다. 응답할 때 findById로 조회한 데이터인 foundCampground를 campground로 할당한다.
			res.render("show", {campground: foundCampground});
		}
	})
});

// "/"형태로 GET METHOD 요청이 들어오면 landing page를 보여준다. 해당 if - else if 형태처럼 포괄하는 Route인 "/"가 코드 위에 있을 경우 모든 페이지가 landing page를
// 응답받는 것을 조심해야 한다. "/campground, /campground/new 등의 url은 결국 "/" 의 하위 형태이기 때문에 해당 Route가 위에 있으면 "/"뒤의 campgound 등은 무시하고
// landing page로 모두 이동시키기 때문이다.
app.get("/", (req, res) => {
	res.render("landing");
})



// express 시 사용하는 기본 서버 설정 내용이다. 해당 코드는 3000포트를 사용할 때의 옵션이며, 정상 연결 시 console log가 출력된다.
app.listen(process.env.PORT || 3000, () =>{ 
	console.log("The Yelpcamp v2 server has been started");
});





 

rendering 시 사용하는 ejs 파일은 310에서 정리

mongodb와 mongoose 연동 시 발생한 에러 제거 방법

 

npm uninstall mongoose ; npm install --save mongoose@5.10.7
// 기존에 설치된 mongoose 삭제 ; @ 뒤의 버전으로 mongoose를 재설치

최신 버전은 https://mongoosejs.com/ 아래의 링크를 확인한다.

 

Mongoose ODM v5.10.7

Let's face it, writing MongoDB validation, casting and business logic boilerplate is a drag. That's why we wrote Mongoose. const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology:

mongoosejs.com

 

 

 

아래와 같이 기존에 사용하던 기능이 deprecated 되거나 port 관련 에러가 발생할 경우 mongoose.connect에 option을 부여한다.

mongoose.connect("mongodb://localhost:27017/yelp_camp", { useNewUrlParser: true, useUnifiedTopology: true});
// 27017은 mongodb에서 사용하는 port

 

 

(node:1159) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser,
 pass option { useNewUrlParser: true } to MongoClient.connect.
(node:1159) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. T
o use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

 

 

이번 lecture에서 배우게 될 내용은 아래와 같다.

1) Add mongoose into app.js
2) connect mongoose and mongodb 
3) setup campgroundSchema 
4) compile schema into model 
5) /campground route로 연결될 경우 db에서 조회 
6) get data from POST /campgrounds and save into mongo

 

해당 소스는 이전에 작성한 YelpCamp/v1을 v2로 복사하여 사용한다. 

 

app.js 

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

// Connection between mongoose and mongodd
// 기존의 UrlParser가 사라질 예정이므로 다음과 같은 에러 발생 시 line 10의 옵션을 사용.  DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.(node:10712) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
mongoose.connect("mongodb://localhost/yelp_camp" , {userNewUrlParser: true, useUnifieldTopology: true});

// express가 bodyParser를 사용하도록 package 호출
app.use(bodyParser.urlencoded({extended: true})); 
// ejs package 호출 (사용 시 ejs 확장자 입력하지 않아도 됨)
app.set("view engine", "ejs");

// MongoDB에서 사용할 Schema setup 
const campgroundSchema = new mongoose.Schema({
	name: String,
	image: String
});

// line 18에서 생성한 campgroundSchema를 컴파일하여 mongoose에서 모델링 후 Campground라는 변수에 저장
const Campground = mongoose.model("Campground", campgroundSchema);

app.get("/campgrounds", (req, res) => {
	// 해당 route에서 보여줄 데이터를 MongoDB로부터 가져온다.
	Campground.find({}, (err, allCampgrounds) => { //Campground라는 collection에서 모든 데이터를 가져온다
		if(err) {
			console.log(err)
		} else {
			res.render("campgrounds", {campgrounds: allCampgrounds});
		}
	})
});


// 클라이언트에서 입력한 데이터를 DB에 저장하는 부분
app.post("/campgrounds", (req, res) => {
	// 클라이언트에서 입력한 name과 image를 변수에 저장
	const name = req.body.name;
	const image = req.body.image;
	// 위의 name과 image를 newCampgroud라는 object에 저장
	const newCampground = {name: name, image: image};
	
    // Create a new campground and save into DB
	Campground.save({newCapground, (err, newlyCreated) => {
		if(err) {
			console.log(err);
		} else {
			// 저장 후 결과를 보여줄 수 있도록 redirect to campground page 
			res.redirect("campgrounds");
		}
	})
});

app.get("/campgrounds/new", (req, res) => {
	res.render("new.ejs");
});

app.get("/", (req, res) => {
	res.render("landing");
});

app.listen(process.env.PORT || 3000, => {
	console.log("The YelpCam v2 server has been started");
});

 

 

 

[그림 1] 정상 적용 시 입력한 데이터는 DB에 저장되어 서버가 리셋되거나 페이지가 새로고침되도 데이터는 persistence 하다.

 

해당 글은 Wonkun Kim님의 [번역] 6개월 안에 풀 스택 개발을 배우는 궁극의 가이드, 단 3만 원으로! 라는 글에서 나오는 풀 스택 개발자 로드맵에 대한 내용입니다. 

 

저는 실제로 아래의 #1에 해당하는 The Web BootCamp by Colt Steele, Udemy의 온라인 코스 강의를 듣고 있습니다. 처음에는 캡션으로 출력되는 한글 자막을 보고 했었는데, 워낙 발음이 깔끔하고 설명을 쉽게 하는 친구라 자막 없이도 들을만 합니다. 

 

또한 모르는 부분이나 잘 안되는 부분에 대해서는 질문을 남기면 보통 1-2일 안에 조교들한테서 답변이 오니까 상당히 피드백도 좋은 편입니다.  

 

무엇보다 해당 코스가 좋은 점은 HTML, CSS, Javascript에 이은 백앤드까지 전체적인 프로젝트가 어떻게 구현되는지 알 수 있다는 점입니다. 총 47시간 405개의 강의인데, 세션 8,9는 넘어가시고 최대한 빨리 한 바퀴 돌리면서 전체적인 흐름을 파악하는게 중요합니다. (블로그에 lecture 별로 강의 내용 정리해놨으니까 혹시 잘 안되시는 부분 있으시면 참조하시거나 질문 주시면 바로 답변 달아드리겠습니다.) 

 

 

 

[번역] 6개월 안에 풀 스택 개발을 배우는 궁극의 가이드, 단 3만 원으로!

웹 개발 공부 가이드 2017년 버전.

medium.com

 

(역자: 이 포스트는 Brandon Morelli The Ultimate Guide to Learning Full Stack Web Development in 6 months,for $30를 번역한 것입니다.)


안녕 친구들! 이 포스트에서 난 어떻게 단, 6개월 안에 그리고 3만 원 이하로 웹 개발에 대해서 거의 모르거나 아예 모르는 상태에서 초급 풀 스택 개발자가 될 수 있는지 보여줄 거야.

이 포스트는 네가 알아야 하는 모든 것을 커버할 거야. 너는 먼저 온라인 코딩 부트캠프로 (1.5만 원) 웹 개발의 기본적인 것들을 배울 거야. 너는 그다음으로 고급 부트캠프를 (1.5만 원) 하게 될 거야. 그다음에, 우리는 네가 첫 두 번의 부트캠프에서 배웠던 모든 것들을 강화하도록 무료 튜토리얼들, 포스트들 그리고 문서로 점프할 거야. 다음으로, 너는 네가 배운 새로운 스킬들을 가지고 몇 가지 프로젝트를 만들고 그것들을 깃허브에 오픈소스화하게 될 거야. 마지막으로, 우리는 이력서 만들기, 인터뷰 준비 그리고 연봉 협상에 집중할 거야.

밝힘: 나는 리뷰들을 쓰고 내가 리뷰한 제품들을 파는 회사들로부터 보상을 받아. 여기에 표현된 모든 의견은 나 자신의 것이야.

이 가이드를 따랐을 때 네가 배우게 될 것들:

  • HTML/CSS
  • jQuery (제이쿼리)
  • JavaScript (자바스크립트)
  • Git/Version Control (깃/버전 컨트롤)
  • React (리액트)
  • Node.js (노드)
  • MongoDB (몽고디비)

준비 됐어? 그럼 들어가 보자고!


#1. 웹 개발 부트캠프

먼저 — 너는 기본적인 것들과 웹 개발 원칙들에 대한 든든한 토대를 마련할 필요가 있어. 이걸 하는 데 여러 방법이 있지만 내 생각에는 가장 좋은 그리고 가장 쉬운 방법이 있다고 생각해.

The Web Developer Bootcamp | Udemy

The only course you need to learn web development - HTML, CSS, JS, Node, and More!

bit.ly

 

콜트 스틸 (Colt Steele)의 웹 개발 부트캠프는 돈으로 살 수 있는 단 하나의 최고의 웹 개발 강좌야. 그건 가끔 2만 원 이하로 세일할 때가 있고, 40시간 이상의 맟춤형 콘텐츠로 채워져 있어.

강사인 콜트 스틸은 온라인 코딩 교육의 세계로 들어오기 전엔 샌프란시스코의 한 코딩 부트캠프의 수석 강사였어. 이 강좌는 그가 오프라인 부트캠프에서 가르쳤던 것의 온라인 버전이야.

이 강좌는 웹 개발의 기본에 대한 모든 것을 다뤄: HTML5, CSS3, 자바스크립트, 부트스트랩, 시맨틱UI, DOM 변형, jQuery, 유닉스 (명령줄 기반) 명령어들.

네가 기본적인 것들을 습득하고 나면, 다음과 같은 더 고급 주제들을 탐험하게 될거야: 노드, NPM, 익스프레스, REST, 몽고디비, 데이터베이스 연계, 인증, PassportJS, 권한 부여.

콜트는 웹 개발에 대해서 잘 알고 있을 뿐 아니라 어떻게 가르치는 줄 아는 강사야. 어려운 개념들을 명료하고 설명하고 모든 것들을 다루기 쉬운 조각들로 나눠. 게다가, 그 강좌는 프로젝트들을 중심으로 돌아가서 너는 지루한 읽기나 시험 보기가 아닌 실제의 것들을 만들면서 배우게 돼.

여기를 클릭해서 더 알아보거나 등록해!


#2. 고급 웹 개발 부트캠프

이제 너는 첫 부트캠프를 다 들었고 풀스택 웹 앱을 어떻게 만드는지 알게 됐으니까 좀 더 깊은 주제를 배울 시간이야. 이 강좌는 네가 아름답고 반응 적인 웹 앱들을 만들 때 사용할 수 있는 좀 더 복잡한 기술들, 프레임워크들과 도구들을 소개하면서 시작해.

The Advanced Web Developer Bootcamp | Udemy

Learn React 16, Redux, D3, ES2015, Testing, CSS Flexbox, Animations, SVG, AJAX, and more!

bit.ly

 

이 고급 웹 개발 부트캠프는 너의 코딩 스킬들을 다음 단계로 올릴 수 있도록 디자인 되었어! 걱정 하지 마, 이 강좌 역시 프로젝트 기반이야. 너는 10개가 넘는 프로젝트를 만들게 될 것이고 네가 모두 이해할 것을 보장하는 솔루션을 포함한 수십 개의 코딩 챌린지를 접하게 될 거야.

이 강좌에서 배우게 될 것들은:

  • CSS3 트랜지션, 트랜스폼 그리고 애니메이션을 배움으로써 CSS 기술을 빌드업
  • 프론트엔드 프레임워크로 들어가서 리액트, 리액트-라우터와 리덕스를 익힘
  • 콜백, 프라미스, 제너레이터와 비동기 함수들뿐 아니라 ES2015, ES2016 그리고 ES2017를 가지고 자바스크립트 기술을 향상
  • 차트, 포스 그래프 그리고 데이터 시각화를 만듦
  • 자스민을 이용한 테스팅
  • D3
  • SVG
  • 노드 API들을 만듦
  • 싱글 페이지 애플리케이션들을 만듦
  • 자바스크립트에서의 객체 지향 프로그래밍
  • 클로져와 ‘this’ 키워드
  • 인증과 권한 부여
  • 자바스크립트를 이용한 비동기 코딩

이 강좌는 거의 350개의 강의와 30시간의 콘텐츠가 있고 너는 정말 많은 것들을 배우게 될 거야.

여기를 클릭해서 더 알아보거나 등록하자!


#3. 배운 기술들 보강

이 시점에 너는 두 개의 온라인 코딩 부트캠프를 들었고 웹 개발 기술들에 대해서 편안함을 느끼기 시작할 거야. 하나의 간단한 아이디어를 가지고 노드 백엔드와 리액트 프론트엔드를 이용해서 멋지게 구현할 수 있을 거야. 더해서, 모바일 우선의 반응성이 있는 페이지를 스타일 할 수 있는 CSS 기술에 대해서 자심감을 가질 거야.

이제 너의 새로운 기술들을 보강하면서 계속 공부할 시간이야. 다음은 문서, 포스트 그리고 튜토리얼의 리스트야.

몇 달 전에 이것들을 읽는 것은 아마도 말도 안 되는 일이 되었겠지만 새로 배운 스킬들과 함께라면 너는 멋지게 그것들을 소화할 수 있어.

내가 제공하는 모든 링크를 다 소화할 필요는 없어. 이것들을 시작점으로 생각해보길 바라.

HTML/CSS

자바스크립트

리액트

풀스택

데이터베이스

배포


#4. [선택사항] 강좌들

더 배우고 싶어? 네가 선택한 주제에 대해 더 깊게 알고 싶다면 내가 추천하는 코스들이 몇 개 있어.


#5. 코딩 게임들

남는 시간에 재밌는 코딩 게임들과 챌린지 사이트를 통해 너의 기술들을 레벨업 하자.


#6. 뭔가를 만들자

이제 멋진 무언가를 만들어! 네가 배운 기술들의 모든 것을 뽐내고 한 아이디어를 개념에서 제품으로 만들어봐!

뭘 만들지 생각해 내는 데 도움이 필요해? 여기에 올바른 방향으로 생각하는 데 도움을 줄 몇 가지 링크가 있어.

너의 프로젝트들을 오픈 소스화 꼭 해서 네가 배운 모든 것들을 뽐내보자. 첫번째 부트캠프에서 깃과 깃허브에 대해서 상당한 깊이로 배우게 될거지만, 네가 그것들에 대해 편하게 느끼지 않는다면 추가의 동기와 도움을 위해 다음 두 링크를 참고해 봐:


#7. 이력서와 포트폴리오

너는 이 스킬들을 배웠고 이제 너의 이력서를 빛나게 하고 포트폴리오를 눈에 띄게 만들 차례야. 이것들을 성취하는 데 도움을 줄 링크들이 여기에 있어.

포트폴리오 만들기

직장 구하는 법

이력서와 링크드인

개인 프로젝트


#8. 인터뷰 준비

너의 이력서와 포트폴리오는 너에게 인터뷰 기회를 가져다줄 거야! 좋았어! 다음 링크들을 사용해서 인터뷰 준비를 해보자:


#9. 연봉 정보

드디어 입사 제의가 들어왔어! 이제 보수에 대해서 협상만 남았어. 도움이 될만한 링크들이 여기 있어:


* 마치며… *

드디어 이 포스트의 마지막까지 왔군… 너의 웹 개발 여행에 행운을 빌어. 확실히 쉽지만은 않을 거야. 하지만 이 가이드를 따름으로써 너는 목표를 이루는 것에 한 발짝 다가간 거야.

내 주간 이메일 리스트에 가입하고 싶다면 여기에 네 이메일을 넣는 것을 고려해봐. 그리고 트위터에서 codeburst를 팔로우하는 것을 잊지 말도록 해.

이번 lecture에서 할 작업은 아래와 같다. 

1. 305. Introduction to Mongoose Pt. 1에서 호출한 cats.js에 mongoose 모델링 생성

2. JS를 통해 mongdb에 실제로 데이터 저장 

3. 저장된 데이터를 retrieve(조회) 

4. 2번 최적화 코드

 

 

1. mongoose 모델링 생성 및 데이터 저장

cats.js

const mongoose = require("mongoose");
mongoose.connection("mongodb://localhost/cats_app", { useNewUrlParser: true}) 
// mongodb 서버가 동작 중일 때는 연결, 동작중이지 않을 때는 서버 구동 후 연결

const catSchema = new mongoose.Schema({
	name: String,
	age: Number,
	temperament: String
});

const Cat = mongoose.model("Cat", catSchema); 
// "Cat"이라는 이름의 catSchema 모델로 컴파일한 후 Cat 변수에 저장한다. 이는 데이터를 7번 라인에 선언한 
// 형태로 저장하기 위함이다. 

// Adding a new cat to the DB
// db에 george를 저장하기 위해 변수 생성
const george = new Cat({
	name: "george",
	age: 11,
	temperament: Grouchy
});

george.save((err, cat) => {
	if(err){
		console.log("Something has went wrong!");
	} else {
		console.log("We've just save a CAT to the db");
		console.log(cat);		// 실제 db에 저장된 cat를 console log로 출력
		console.log(george);	// 19라인에서 저장된 george를 console.log로 출력
	}
});

 

[그림 1] mongoDB에 실제로 저장된 후 console log에 찍힌 메세지

하지만 실제로 console log에 찍힌 값은 db에서 조회된 데이터가 아닌 저장 시 db에 전달한 값일 뿐이다.

 

 

2. db에 저장된 데이터를 실제로 조회

cats.js

const mongoose = require("mongoose");
mongoose.connection("mongodb://localhost/cats_app", { useNewUrlParser: true}) 
// mongodb 서버가 동작 중일 때는 연결, 동작중이지 않을 때는 서버 구동 후 연결

const catSchema = new mongoose.Schema({
	name: String,
	age: Number,
	temperament: String
});

const Cat = mongoose.model("Cat", catSchema); 
// "Cat"이라는 이름의 catSchema 모델로 컴파일한 후 Cat 변수에 저장한다. 이는 데이터를 7번 라인에 선언한 
// 형태로 저장하기 위함이다. 

// Adding a new cat to the DB
// db에 george를 저장하기 위해 변수 생성
const george = new Cat({
	name: "george",
	age: 11,
	temperament: Grouchy
});

george.save((err, cat) => {
	if(err){
		console.log("Something has went wrong!");
	} else {
		console.log("We've just save a CAT to the db");
		console.log(cat);		// 실제 db에 저장된 cat를 console log로 출력
		console.log(george);	// 19라인에서 저장된 george를 console.log로 출력
	}
});



// DB에 저장된 모든 값을 조회한다. 
Cat.find({}, (err, cats) => {
	if(err){
		console.log("Oh no, Error has been occured!");
        console.log(err);
	} else {
		console.log("All the cats are... ");
		console.log(cats);
	}
});


 

3. 1에서 george라는 변수에 고양이의 데이터를 저장한 후, 그 데이터를 다시 db로 전달하였다. 이를 하나의 코드로 작성한다.

 

cats.js

const mongoose = require("mongoose");
mongoose.connection("mongodb://localhost/cats_app", { useNewUrlParser: true}) 
// mongodb 서버가 동작 중일 때는 연결, 동작중이지 않을 때는 서버 구동 후 연결

//const catSchema = new mongoose.Schema({
//	name: String,
//	age: Number,
//	temperament: String
//});

const Cat = mongoose.model("Cat", catSchema); 
// "Cat"이라는 이름의 catSchema 모델로 컴파일한 후 Cat 변수에 저장한다. 
// 이는 데이터를 7번 라인에 선언한 형태로 저장하기 위함이다. 

// Adding a new cat to the DB
// db에 george를 저장하기 위해 변수 생성
//const george = new Cat({
//	name: "george",
//	age: 11,
//	temperament: Grouchy
//});

//george.save((err, cat) => {
//	if(err){
//		console.log("Something has went wrong!");
//	} else {
//		console.log("We've just save a CAT to the db");
//		console.log(cat);		// 실제 db에 저장된 cat를 console log로 출력
//		console.log(george);	// 19라인에서 저장된 george를 console.log로 출력
//	}
//});


Cat.create({			// catSchema로 작성된 Cat이란 변수에 아래의 값을 추가한다.
	name: "Korean short",
	age: 2,
	temperament: "cute"
	}, (err, newCat) => {
		if(err){
			console.log(err);
		} else {
			console.log(newCat);
		}
})


// DB에 저장된 모든 값을 조회한다. 
Cat.find({}, (err, cats) => {
	if(err){
		console.log("Oh no, Error has been occured!");
        console.log(err);
	} else {
		console.log("All the cats are... ");
		console.log(cats);
	}
});


 

[그림 2] cats.js 구동 시 console log에 출력되는 내용. 2개의 george 중 1개는 실제 db로 저장되는 값, 나머지 1개는 저장하기 위해 JS로 변환시켜놓은 값이다. 

 

[그림 3] mongoDB에 실제로 저장된 데이터 

 

Mongoose란?

: Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.(mongoosejs.com/)

 

 

Mongoose를 사용하는 이유

: Mongoose를 사용하여 Javascript와 MongoDB를 연결하여 사용할 수 있다. 즉 Javascript 코드를 통해 CRUD(Create, Read, Update, Delete) 가능하다.

 

Mongoose 설치 

: # npm install mongoose 

 

[그림 1] Installation of the mongoose

 

Javascript에서 mongoose 사용 방법

const mongoose = require("mongoose"); //mongoose 패키지 로드
mongoose.connect("mongodb://localhost/cat_app", { userNewUrlParser: true}); // mongoose와 mongdb를 연결한다.

const catSchema = new mongoose.Schema({ 
// DB에 사용될 schema를 정의한다. 아래와 같이 3개의 Key-Value 쌍을 가진 데이터를 생성
	name: String,
	age: Number,
	temperament: String
});   

const Cat = mongoose.model("Cat", catSchema); 
//catSchema를 mongoDB 모델로 컴파일한다. 즉 위에서 선언된 catSchema 각각의 Key-Value 모델을 Cat에 저장하여
// mongo shell 에서 사용하듯 작업할 수 있는 모델로 변경한다. 

Hi everyone,

This note covers many different errors and warnings that you may encounter when working with mongoose (covered in the next couple of lectures):


July 7th, 2020 - Update

Your mongoose.connect() code should look like this:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/db_name', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('Connected to DB!'))
.catch(error => console.log(error.message));

You may not recognize all of the syntax used above, please see below for additional resources:
Not familiar with const? Learn more here.
Not familiar with .then() and .catch()? Learn more here.
Not familiar with arrow => functions? Learn more here.


April 21st, 2019 - Update

See here for the official documentation with instructions on how to solve all deprecation warnings with mongoose (listed in previous updates, below).


October 14th, 2018 - Update

If you're getting an error like this: DeprecationWarning: collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.

then please see here.

or if you're getting: DeprecationWarning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.

then see here.


September 18th, 2018 - Update:

If you're getting an error like this: DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.

then please see here.


August 23rd, 2018 - Update:

If you're getting an error like this: DeprecationWarning: collection.find option [fields] is deprecated and will be removed in a later version.

then see here for an explanation of what's going on.
(TL;DR: you can ignore this warning)

 

July 5th, 2018 - Update:

If you're getting an error like this: UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): MongoError: port must be specified  

or this:

DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect. 

..then see here for the solution.


Previous Notes:

In the last lecture Colt mentioned being able to limit how many documents you could remove by chaining .limit() onto the .remove() command in mongodb. However, that was a slight oversight and that specific syntax won't work. Please see here for an example of the correct syntax.

Meanwhile, in the next few lectures you will learn about an Object Document Modeling (ODM) package for Express called Mongoose.

You may run into two different warnings in your terminal regarding the deprecation of mpromise and open(), they will look like this:

  1. Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library
  2. instead: http://mongoosejs.com/docs/promises.html

and this:

  1. `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead,
  2. or set the `useMongoClient` option if using `connect()` or `createConnection()`

Neither of these warnings should happen anymore if you're using MongoDB 3.6.x (or newer) and Mongoose 5.x.x (latest version) see here for instructions on how to update if you don't already have the latest versions of both MongoDB and Mongoose.

*Note: You may want to bookmark this lecture and come back to it if you run into either of the warnings mentioned above

cheers,
Ian

Note about installing MongoDB

 

September 7th 2020 Update (important, please read carefully):

Hi there,

Please note that your Goorm container already has MongoDB installed if you followed the instructions linked in lecture 248.

If for whatever reason your Goorm container does not have MongoDB installed, then please follow these instructions to add MongoDB to your existing Goorm container.

To run the mongod server in your container, simply type mongod in the terminal window/tab and press enter/return.

This will start the server that is required for you to connect to the mongo shell or connect to a mongodb database in your node applications.

You must leave mongod running in its own terminal while you are working with either the mongo shell or a node app that requires a database. Once you are done working you may return to the mongod terminal tab and turn it off by pressing ctrl+d (that is control and d at the same time).

You can run the mongo shell (where you will access your databases directly) in another terminal window/tab by running the mongo command. Once inside of the shell, you can run the commands that will be taught in the next lecture. To exit the shell type exit and press enter/return (or just press ctrl+d).

As a side note: In the Mongo Shell Basics video that follows, you will see Colt use the show collections command which will show something called system.indexes . This will no longer show up in the latest versions of MongoDB. You can read more about this here.

-------
Thanks,
Ian

+ Recent posts