Open In App

Mongoose updateOne() Function

The updateOne() function is used to update the first document that matches the condition. This function is the same as update(), except it does not support the multi or overwrite options.

Syntax:



Model.updateOne(id)

Parameters:

Steps to Installation of Mongoose Module:

Step 1: You can install this package by using this command.



npm install mongoose

Step 2: After installing the mongoose module, you can check your mongoose version in the command prompt using the command.

npm version mongoose

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"mongoose": "^7.6.5",
}

Example: Below the code example for the updateOne() method:




const mongoose = require('mongoose');
 
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true,
    useFindAndModify: false
});
 
// User model
const User = mongoose.model('User', {
    name: { type: String },
    age: { type: Number }
});
 
// Find all documents matching the condition
// (age >= 5) and update first document
// This function has 4 parameters i.e.
// filter, update, options, callback
User.updateOne({age:{$gte:5}},
    {name:"ABCD"}, function (err, docs) {
    if (err){
        console.log(err)
    }
    else{
        console.log("Updated Docs : ", docs);
    }
});

Steps to run the program:

node index.js

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:

Console Output:

After the function is executed, You can see the database as shown below:

So this is how you can use the mongoose updateOne() function which is used to update the first document that matches the condition. This function is the same as the update(), except it does not support the multi or overwrite options.

We have a mongoose queries complete reference where we covered all the mongoose queries to check those please go through Mongoose Queries article.


Article Tags :