ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • nodejs에서 mongoose로 mongDB 다루기
    database 2019. 5. 30. 22:32

     

     

    mongDB

    NoSQL DB 중 하나

    NoSQL=관계형 데이터베이스가 아님. 기존 SQL 표준을 사용하지않음

    mongDB는 자바스립트로 DB제어가능

     

    RDBMS와 용어 차이

    RDBMS     /    mongDB

    시스템단위 => Cluster

    데이터베이스 => Collection

    릴레이션(테이블) => Model

    튜플(행) => Document

     

     


     

    mongoDB atlas

     

     

     

     

     


     

    mongoose

     

     

     

     

     

    mongoose 객체 가져오기

    const mongoose = require('mongoose');

     

    • 연결 URL

    mongodb+srv://DB유저이름:유저비밀번호@DB주소:포트주소/데이터베이스이름

     

    포트주소 기본값 : 27017

     

     

    데이터베이스 연결

    mongoose.connect(
    	url,			//mongDB 연결주소
    	option,			//객체로전달
    	callback		//error인자를 
    )
    //예시
    function connect(){
    	mongoose.connect(myDBUrl, {useNewUrlParser : true}, err=>{
    	if(err){
    	console.error("DB Connection Error :", err);
    	}
    	else console.log("Connected");
    	});
    }

     

     

     

    mongoose의 Model 스키마

    const Schema = mongoose.Schema;		//Schema 클래스 반환
    const mySchema = new Schema({		//Schema 객체 생성
    	
    });
    //예시
    const userSchema = new mongoose.Schema({
      name: String,
    });

     

     

    Model 사용

    mongoose.model(모델이름, 모델스키마);
    //예시
    mongoose.model('User', userSchema);  //실제 DB에선 users 모델로 연결

    모델이름은 실제 컬렉션에선 소문자 복수형으로 찾는다.(User => users)

    만약 이러한 변환이 싫으면

    { collection: 모델이름지정 } 사용

     

     

     

    Document

     

    *model()의 반환값은 생성자이다.

    const UserModel = mongoose.model('User', userSchema);

    반환된 생성자를 통해 하나의 Document를 다룰 수 있다.

     

     

    Model에 Document 추가하는 방법 2가지

    //예시1
    const user1 = UserModel({ name : "imar" });
    //예시2
    const user1 = UserModel();
    user1.name = "imar";

    추가하고 save() 호출시 만약 실제로 해당하는 Collection과 Model이 없으면

    자동으로 생성해서 Document를 추가한다.

     

     

    save() : 실제 시스템에 Document 추가 반영

    document.save().then(callback)	//여기서 document는 model생성자로 생성한 객체이다.
    //예시
    user1.save().then(()=>console.log("saved.."));

    save()는 프로미스를 반환한다.

     

     

     

     

Designed by Tistory.