Web

Mongoose | 업데이트/삭제/스키마/메서드/미들웨어

taenyLog 2023. 6. 25. 07:35
반응형



Mongoose로 업데이트하기
클래스이름.updateOne({기존값},{바꿀값}) 첫 번째 항목을 갱신
즉, 쿼리에 매치되는 첫 번째 항목을 우리가 제시한 것으로 갱신

클래스이름.updateMany({기존값},{바꿀값}) 
Movie.updateMany({title:{$in:['Amadeus','Stand By Me']}},{score:10})
'Amadeus'와 'Stand By Me'의 title을 가진 데이터의 score를 10으로 변경

findOneAndUpdate() 
쿼리가 실행된 후 갱신된 버전을 돌려받거나 기본적으로 새 버전이 표시되게 만들고 싶을 경우 옵션을 하나 더 지정해야함
그 옵션을 세 번째 인수로 전달해야함. new라는 옵션 객체인데 false가 디폴트이다. true로 변경해야 원래 문서 말고 수정된 문서 표시됨
Movie.findOneAndUpdate({title :'GOOD DAY'},{score : 7.8}, {new : true})

https://mongoosejs.com/docs/tutorials/findoneandupdate.html
https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate/




Mongoose로 삭제하기
findOneAndRemove()
 https://mongoosejs.com/docs/api/model.html#Model.findOneAndRemove() 

update나 delete 수행시 데이터가 반환되지 않는다. 수정/삭제 개수 확정 메세지만 반환
findOneAndUpdate() / findOneAndRemove() 메서드쓰면 문자 반환됨.




Mongoose 스키마 유효성 검사
Mongoose는 버퍼링을 작동해서 시작한다. 버퍼링으로 우리가 정의하는 모델을 즉시 사용

1.mongoose.connect 연결
const mongoose = require("mongoose");
mongoose
  .connect("mongodb://127.0.0.1:27017/shopAPP")
  .then(() => {
    console.log("CONNECTION");
  })
  .catch((err) => {
    console.log("ERROR ");
    console.log(err);
  });

2. 스키마 생성
  const productSchema = new mongoose.Schema({
    name:{
        type:String
    },
    price :{
        type:Number
    }
  })
3. 모델 생성
const Product = mongoose.model('Product',productSchema)




추가 스키마 제약조건
https://mongoosejs.com/docs/schematypes.html
All Schema Types
required: boolean or function, if true adds a required validator for this property
default: Any or function, sets a default value for the path. If the value is a function, the return value of the function is used as the default.
select: boolean, specifies default projections for queries
validate: function, adds a validator function for this property
get: function, defines a custom getter for this property using Object.defineProperty().
set: function, defines a custom setter for this property using Object.defineProperty().
alias: string, mongoose >= 4.10.0 only. Defines a virtual with the given name that gets/sets this path.
immutable: boolean, defines path as immutable. Mongoose prevents you from changing immutable paths unless the parent document has isNew: true.
transform: function, Mongoose calls this function when you call Document#toJSON() function, including when you JSON.stringify() a document.



Mongoose 업데이트 유효성 검사
뭔가를 만들면 유효성 검사가 자동으로 적용되는데 그게 업데이트되고 나서는 Mongoose한테 계속 유효성 검사를 적용하라고 해줘야함.
예 > findOneAndUpdate()는 
runValidators : true 를 써주면된다.




Mongoose 업데이트 검사 오류
  size:{
    type:String,
    enum:['S','M','L']
  }
enum으로 유효한 여러 개의 값을 설정할 수 있다.




인스턴스 메서드
모델을 통해 생성된 인스턴스에서 사용가능한 메서드
!! 화살표가 아닌 기존의 함수식으로 써야함 !! ( 함수의 값이 변하기 때문에)
https://mongoosejs.com/docs/guide.html#methods




정적 메서드 추가
모델 자체에서 사용가능한 메서드 




가상 Mongoose      
Virtuals
실제 데이터베이스 자체에 존재하지 않는 스키마에 특성을 추가할 수 있게 해준다.
first와 last가 있는 user Model이 있다. fullName에 접근하고 싶을 때 데이터베이스에 저장할 필요는 없고, 데이터베이스에 있는 것처럼 접근할 수 있는 특성을 만들자




Mongoose를 미들웨어로 정의하기
미들웨어 (Middleware)
데이터에서의 미들웨어 사용은 사용자가 저장하기 전 어떠한 규칙이 적용되었는지 체크할 수 있고 암호 같은 경우 보안이 중요하기에 저장하기전 어떠한 함수를 부여한 후 POST 되게 할 수 있는 역할을 한다

미들웨어(Middleware,pre,post hook)는 비동기 함수를 실행하는 동안 제어가 전달되는 함수로 미들웨어는 스키마 수준에서 지정되며 플러그인 작성에 유용하다.

Mongoose는 특정 작업 실행 전후에 코드를 실행하게 해준다
어떤 것이 삭제되거나 저장되기 직전이나 함수를 호출할 때도 코드를 실행할 수 있다
작업할 수 있는 전체 목록을 볼 수 있고, pre혹은 post hook 혹은 미들웨어를 실행할 수 있다.
메소드를 만들 땐, 스키마를 모델화 하기전에 정의한다

 

 

반응형