Language

[udemy] Web Developer : Mongoose

jaewpark 2022. 5. 23. 11:58
Movie.updateOne({title: 'Amadeus'}, {year: 1984}).then(res => console.log(res))

mongoose 설치 및 mongo에 연결

npm init -y
npm i mongoose
touch index.js
// index.js
const mongoose = require('mongoose');

main().catch(err => console.log(err));

async function main() {
  await mongoose.connect('mongodb://localhost:27017/movieApp');
}

const movieSchema = new mongoose.Schema({
  title: String,
  year: Number,
  score: Number,
  genre: String
})

const Movie = mongoose.model('Movie', movieSchema);

const amadeus = new Movie( { title: ...입력 })

 

node load

> node
> .load index.js
이후 터미널에서 아래와 같은 명령어를 실행할 수 있다.

 

mongoose 삽입 (공식)

// 대량 삽입
Movie.insertMany([
  { title: ...입력,
  { title: ...입력,
  ...
])
  .then(data => {
    console.log("IT WORKED")
    console.log(data);
  })

 

mongoose 찾기 (공식)

// 모든 데이터
Movie.find({}).then(data => console.log(data))

// 특정 데이터
Movie.find({year: {$lt: 1990}}).then(data => console.log(data))

// 첫번째 항목의 데이터만
Movie.findOne({}).then(m => console.log(m))

 

mongoose 업데이트 (공식)

// 데이터 하나만 업데이트
Movie.updateOne({title: 'Amadeus'}, {year: 1984}).then(res => console.log(res))

// 여러 데이터 업데이트
Movie.updateMany({title: {$in: ['Amadeus', 'Stand By Me'}}, {score: 10}).then(res => console.log(res))

Movie.findOneAndUpdate({title: 'The Iron Giant'}, {score: 7.8}, {new: true}).then(m => console.log(m))

 

mongoose 삭제 (공식)

Movie.remove({title: 'Amelie'}).then(msg => console.log(msg))

Movie.deleteMany({year: {$gte: 1999}).then(msg => console.log(msg))

Movie.findOneAndDelete({title: 'Alien'}).then(m => console.log(m))

 

스키마 제약 조건 설정

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    maxlength: 20
  },
  price: {
    type: Number,
    required: true,
    min: 0
  },
  onSale: {
    type: Boolean,
    default: false
  },
  catagories: [String],
  qty: {
    online: {
      type: Number,
      default: 0
    },
    inStore: {
      type: Number
      default: 0
    }
  }
});