Trusted answers to developer questions

What is update() in Mongoose?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

When using Mongoose, it is very likely that you will want to update a document.

One good method to use is the update() method. It matches a document based on the filter specified, and then makes the update based on the update supplied as well. However, the update() function does not return the updated document but returns a write result.

Syntax

Model.update({filter}, {update})

Parameters

filter: The filter is the match for documents that you wish to update.

update: This is also an object that contains what needs to be updated in the documents matched.

callback: It can also take a callback function that can do something to documents after they are returned.

Return value

It does not return the updated document but returns a write result.

Code

The following example shows how to use the update() function. We will supply it with a filter and the update we wish to make. Lastly, we will display the output to the console.

// import mongoose
const mongoose = require("mongoose");
// creating a Schema with mongoose
let Person = mongoose.model("Person", new mongoose.Schema({
name: String,
role: String,
hasALife: Boolean
})
)
// make a query with the `updateMany()` function
const person = await Person.update({ role: "Theodore" }, {hasALife: true})
console.log(person) // {n: 1, nModified: 1}

In the example above, the result returned was an object that contains the following:

  • n: This is the number of documents that match the filter.
  • nModified: This is the number of elements modified or updated.

RELATED TAGS

mongodb
mongoose
update()

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
Did you find this helpful?