오락기/mongoDB

mongoose.js node 연동

문방구앞오락기 2018. 8. 17. 13:29

import mongoose from 'mongoose' 

let db = mongoose.connection 

db.on('error'console.error); 

db.once('open', () => { 

// CONNECTED TO MONGODB SERVER 

console.log("Connected to mongod server"); 

}); 

mongoose.connect('mongodb://jsplays.iptime.org:27017/resource') 

 

커넥션  이렇게 

mongoose.connect('mongodb://username:password@host:port/database?options...'); 

 

 

let schema = mongoose.Schema 

let testSchema = new schema({ 

title : String, 

auth : String, 

date : { type : Date , default : Date.now} 

}) 

 

 

스키마 지정 

사용되는 스키마는 8종류 

 

  1. String 

  2. Number 

  3. Date 

  4. Buffer 

  5. Boolean 

  6. Mixed 

  7. Objectid 

  8. Array 

 

import mongoose from 'mongoose' 

const schema = mongoose.Schema 

const testSchema = new mongoose.schema ({ 

test : {type : Number , require : true , unique : true}, 

title : String, 

auth : String, 

date : { type : Date , default : Date.now} 

}, 

{ 

timestamps: true 

} 

) 

//콜렉션 이름을 지정하고싶으면 스키마 생성시 옵션으로 넣는다 

// const todoSchema = new mongoose.Schema({..}, { collection: 'my-collection-name' }); 

//모델은 생성자이므로 인스턴스를 생성할수있음으로 속성이나 값을 추가하여 생성할수있다 

const Test = mongoose.model('Test' , testSchema) 

const test = new Test({ 

test : 1, 

title: 'test', 

auth : 'js' 

}) 

또는 

const test = new Test() 

test.test = 1 

test.title = 'test' 

test.auth = 'js' 

const output = mongoose.model('Test' , testSchema) 

export default output 

 

 

관계는 이렇게 될수있다.