There are multiple ways to update 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 an existing document or create a new one before calling the save() method.

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

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:

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:

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:

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:

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:

const id = '454333e4'

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

doc.name // Macbook Pro

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.