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.
Model.update({filter}, {update})
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.
It does not return the updated document but returns a write result.
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 mongooseconst mongoose = require("mongoose");// creating a Schema with mongooselet Person = mongoose.model("Person", new mongoose.Schema({name: String,role: String,hasALife: Boolean}))// make a query with the `updateMany()` functionconst 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.