• Home
  • About
    • lahuman photo

      lahuman

      열심히 사는 아저씨

    • Learn More
    • Facebook
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

Mongoose에서 Array 내용 수정 후 .save()를 호출해도 동작하지 않는 현상

26 Nov 2020

Reading time ~1 minute

Mongoose에서 Array 내용 수정 후 .save()를 호출해도 동작하지 않는 현상

다음과 같은 mongo Model이 존재 할때,

const mongoose = require('mongoose');

const { Schema } = mongoose;

const Confirm = new Schema({
  type: { type: String, require: true, index: true },
  pgm_id: { type: Number, require: true, index: true },
  confirm: { type: Array, index: true },
  brd_dtm: { type: Date, require: true, index: true },
}, { timestamps: true });

module.exports = mongoose.model('Confirm', Confirm);

다음과 같은 데이터가 있다고 가정했을때,

{
    type: 'A',
    pgm_id: 1234,
    confirm:[0,0,0],
    brd_dtm:  ISODate("2020-11-26T05:51:37.970Z")

}

모델을 조회 후 수정하였고, 저장했다.

const result = await Confirm.findOne({pgm_id: '1234'});

result.confirm[3] = 10;

await result.save();

console.log(await Confirm.findOne({pgm_id: '1234'}));

결과는 데이터가 변경되지 않습니다.

Array의 경우 수정을 하고 저장을 해도 처리가 되지 않습니다. 단 Array를 새로 만들어서 넣을 경우는 반영됩니다.

하지만 매번 Array를 새로 만들기 보다 쉽게 하는 방법은 다음과 같습니다.

const result = await Confirm.findOne({pgm_id: '1234'});

result.confirm[3] = 10;

//변경된 사항을 강제 처리
result.markModified('confirm');

await result.save();

이렇게 하는 방식도 있다!

참고자료

  • Mongoose instance .save() not working


nestjsmongoosesave Share Tweet +1