![]() |
VOOZH | about |
In Mongoose, the update() function is used to modify a document in a MongoDB collection based on a given filter. It updates a document but does not return the updated document itself. This function is part of Mongoose’s Query API and is a powerful tool for managing data in your Node.js applications. In this article, we will walk us through the update() function, its syntax, usage, and common examples.
update() Function?The update() function in Mongoose is used to update one or more documents in a MongoDB collection that match a specified condition. This function performs an update operation but does not return the updated document.
Instead, it returns information about the operation, such as how many documents were affected by the update. While update() modifies documents, if you need to get the updated document after modification, you should use the findOneAndUpdate() method instead.
Model.update(query, update, options, callback);
$set, $inc).multi (to update multiple documents).pdate() Function in MongooseThe update() function is commonly used when you need to modify one or more fields in a document without needing the updated document as a response. Now that we understand the basics, let’s go through some examples to see how the update() function works in practice.
In this example, we will connect to a MongoDB database and update a user document by changing the user's name. The updated document will not be returned.
Filename: index.js
const mongoose = require('mongoose');
// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
// Define the User model
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number }
});
// Update the user's name from "Amit" to "Gourav"
User.update({ name: "Amit" }, { $set: { name: "Gourav" } }, function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Result:", result); // Will show how many documents were updated
}
});
update() function is used to update a document with the name "Amit" to change it to "Gourav".$set operator is used to specify the field to be updated.Follow these steps to run the Mongoose update() example:
Make sure you have installed mongoose module using following command:
npm install mongooseThe project structure will look like this: 👁 project structure
Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below: 👁 Database
To execute the program, navigate to your project folder and run:
node index.js👁 ImageYou can use a GUI tool like Robo3T or MongoDB Compass to see the database. After running the update function, you should see the document’s name updated from "Amit" to "Gourav".
👁 new DatabaseSo this is how you can use the mongoose update() function which updates one document in the database without returning it.
In this example, we’ll update the age of users who are over 18 years old.
// Filename: index.js
const mongoose = require('mongoose');
// Database connection
mongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
// User model definition
const User = mongoose.model('User', {
name: { type: String },
age: { type: Number },
});
// Update users who are over 18 and increase their age by 1
User.update({ age: { $gt: 18 } }, { $inc: { age: 1 } }, { multi: true }, (err, result) => {
if (err) {
console.log('Error:', err);
} else {
console.log('Update Result:', result); // Shows how many documents were updated
}
});
update() function is used with a filter to find users who are older than 18 ({ age: { $gt: 18 } }).$inc operator is used to increment the age field by 1.multi: true option allows us to update multiple documents that meet the condition.Before using the update() function or any other Mongoose features, make sure to set up a Node.js application and install the Mongoose module.
To set up a new Node.js application, run the following commands:
mkdir folder_name
cd folder_name
npm init -y
touch index.js
After initializing the Node.js application, install Mongoose using npm:
npm install mongooseTo confirm that Mongoose has been installed, check the version by running:
npm version mongooseThe update() function in Mongoose is a useful tool for updating documents in a MongoDB collection based on a specified condition. While it does not return the updated document, it provides a simple and efficient way to modify data. For more complex scenarios where you need the updated document, consider using methods like findOneAndUpdate(). By understanding how to use the update() function, you can streamline your database operations and make your application more efficient when working with MongoDB through Mongoose.