Mongoose를 이용해 JavaScript파일을 MongoDB에 연결하고 정보 수정
schema(스키마)는 Mongo의 각기 다른 키 집합을 JavaScript의 다른 타입으로 구조를 짜는 것을 말한다.
JS나 기타 언어에서 다른 타입인 데이터를 Mongo로부터 가져오지만 그 언어에 데이터 타입이 있을 수도 있고 없을 수도 있다.
스키마를 정의함으로써 구체화한다.
https://mongoosejs.com/docs/guide.html
Mongoose v7.3.1: Schemas
If you haven't yet done so, please take a minute to read the quickstart to get an idea of how Mongoose works. If you are migrating from 6.x to 7.x please take a moment to read the migration guide. Everything in Mongoose starts with a Schema. Each schema ma
mongoosejs.com
import mongoose from 'mongoose';
const { Schema } = mongoose;
const blogSchema = new Schema({
title: String, // String is shorthand for {type: String}
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});
자바스크립트에서 새로운 정보를 만들고 데이터를 전달하면 JavaScript 객체가 되고 메서드를 사용할 수 있다.
-----VSCode
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/movieApp')
.then(()=>{
console.log("CONNECTION")
})
.catch(err=>{
console.log("ERROR ")
console.log(err)
})
const movieSchema = new mongoose.Schema({
title:String,
year:Number,
score:Number,
rating : String
})
// Movie라는 모델 클래스 생성
const Movie = mongoose.model('Movie',movieSchema)
// model이름을 나타내는 문자열은 대문자
// 클래스(Movie)는 주로 모델 이름(Movie)과 똑같이 입력함
const Amadeus = new Movie({title:'Amadeus',year:1986, score:9.2, rating:'R'})
// Movie라는 새로운 인스턴스를 생성
자바스크립트에서 클래스를 생성 후 확인해보자
git bash 로 node 연결하여 자바스크립트에서 만든 Amadeus 확인
----- Git Bash
$ node
Promise {
<pending>,
[Symbol(async_id_symbol)]: 139,
[Symbol(trigger_async_id_symbol)]: 138
}
> CONNECTION
> Amadeus
{
title: 'Amadeus',
year: 1986,
score: 9.2,
rating: 'R',
_id: new ObjectId("64973665b62ff8491f1f1745")
}
----Power Shell
movieApp> db.movies.find()
[
{
_id: ObjectId("64973665b62ff8491f1f1745"),
title: 'Amadeus',
year: 1986,
score: 9.2,
rating: 'R',
__v: 0
}
]
Git Bash에서 정보를 수정하여보자
----Git Bash
> Amadeus.score = 9.5
9.5
수정후 파워셸에서 확인하면 이전의 정보와 동일하게 9.2가 나타난 것을 볼 수 있다.
----Power Shell
movieApp> db.movies.find()
[
{
_id: ObjectId("64973665b62ff8491f1f1745"),
title: 'Amadeus',
year: 1986,
score: 9.2,
rating: 'R',
__v: 0
}
]
Git Bash에서 save 해주면 PowerShell도 수정됨
----Git Bash
> Amadeus.save()
Promise {
<pending>,
[Symbol(async_id_symbol)]: 1182,
[Symbol(trigger_async_id_symbol)]: 5
}
----Power Shell
movieApp> db.movies.find()
[
{
_id: ObjectId("64973665b62ff8491f1f1745"),
title: 'Amadeus',
year: 1986,
score: 9.5,
rating: 'R',
__v: 0
}
]