https://masteringjs.io/tutorials/mongoose/update 의 내용을 번역 및 발췌합니다.
Mongoose는 document를 update하는 4가지 방법을 제공해준다:
Mongoose model document에 save
method를 사용하여 update를 진행하는 것이다.
주로 find
계열의 method를 사용하여 mongoose model document를 가져와서 원하는 수정사항을 적용한 뒤 save
method로 update를 진행하는 방향으로 진행된다:
const doc = await PersonModel.findOne({ name: 'woo' })
doc.age = 30
await doc.save()
Database에서 document를 load하지 않고 update하는 방법에 사용된다. 아래의 예시에서 name: 'woo'
인 사람의 document는 Node.js process memory에 올라가지 않게 된다:
await PersonModel.updateOne({ name: 'woo' }, {
age: 30
})
Mongoose에서는 가능한한 save
method를 사용할것을 권장한다. 하지만 updateOne
이나 updateMany
가 이점을 가지는 경우들도 있다:
updateOne
은 atomic하다. find
계열의 method로 document를 가져와서 내용을 수정하고 save
하는 동안에 document의 수정이 일어날 수 있다.updateOne
은 document를 memory에 올리지 않고도 사용이 가능하다. Document의 크기가 큰 경우에는 더 나은 performance를 기대해볼 수 있다.Model.updateOne
의 syntactic sugar이다. 이미 memory에 document가 존재하는 경우 이는 Model.updateOne
을 호출해준다.
보통의 경우 잘 사용되지 않는다. save
와 Model.updateOne()
이 사용되고는 한다.
Model.findOneAndUpdate
나 이것과 유사한 Model.findByIdAndUpdate
는 updateOne
과 비슷하게 동작한다. Match되는 제일 첫 document를 atomic하게 update시킨다.
updateOne
과 가장 큰 차이점으로는, 이 method에서는 update가 완료된 document를 반환시켜준다는 점이다.
Atomic | Doc in memory | Returns updated doc | Change Tracking | |
---|---|---|---|---|
Document#save() | X | O | O | O |
Model.updateOne() | O | X | X | X |
Model.updateMany() | X | X | X | X |
Document#updateOne() | X | O | X | X |
Model.findOneAndUpdate() | O | X | O | X |