# How to update documents in Mongoose

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jul 9, 2022. Topics: Node.js, Mongoose, MongoDB.
Canonical URL: https://attacomsian.com/blog/mongoose-update-documents

> Learn how to update documents in Mongoose using save, updateMany, updateOne, and findOneAndUpdate methods.

There are multiple ways to update [documents](https://attacomsian.com/blog/mongoose-documents) in Mongoose. You can either use the `save()`, `updateOne()`, `updateMany()`, or `findOneAndUpdate()` method.

## `save()` method

The `save()` method is available on the `Document` class. It means that you first need to [find](https://attacomsian.com/blog/mongoose-find-documents#find-a-single-document) an existing document or create a new one before calling the `save()` method. 

Here is an example of using `save()` to update a document:

```javascript
const mongoose = require('mongoose')
const { Schema } = mongoose

const Product = mongoose.model(
  'Product',
  new Schema({
    name: String,
    color: String,
    price: Number
  })
)

// Create a document
const product = await Product.create({ name: 'iPhone 13', color: 'Gold', price: 1199 })

// Modify document
product.price = 1250

// Save changes
await product.save()
```

## `updateMany()` method

The `updateMany()` method updates all matching documents in the database. This method is used to update multiple documents, without loading them first in memory.

Here is an example of using `updateMany()` to increment all black products prices by 10:

```javascript
const res = await Product.updateMany({ color: 'Black' }, { $inc: { price: 10 } })

res.matchedCount // Number of documents matched
res.modifiedCount // Number of documents modified
res.acknowledged // Boolean indicating everything went smoothly.
```

## `updateOne()` method

The `updateOne()` method is similar to `updateMany()` except that MongoDB will update only the first document that matches filter:

```javascript
const res = await Product.updateOne({ name: 'iPhone 13' }, { color: `Black` })
```

If you want to overwrite an entire document rather than updating specific fields, use the `replaceOne()` method instead:

```javascript
const res = await Product.replaceOne(
  { name: 'iPhone 13' }, 
  { name: 'Macbook Pro', color: `Black`, price: 2599 }
  )
```

## `findOneAndUpdate()` method

The `findOneAndUpdate()` method also updates the first document that matches the given filter. Unlike `updateOne()`, it returns the updated document:

```javascript
const doc = await Product.findOneAndUpdate(
  { name: 'iPhone 13' }, 
  { name: 'Macbook Pro' }, 
  { new: true }
  )

doc.name // Macbook Pro
```

This function has another variant called `findByIdAndUpdate()` used to find a document by its `_id` field value and then update it:

```javascript
const id = '454333e4'

const doc = await Product.findByIdAndUpdate(id, { name: 'Macbook Pro' }, { new: true })

doc.name // Macbook Pro
```
