Open In App

Mongoose updateOne() Function

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Model: This is the name of the collection used to retrieve the document corresponding to the provided ID.
  • id: This is the identifier for the document you intend to locate.
  • callback: `updateOne` also accepts a callback function, which can manage errors or perform actions with the retrieved document.

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:

NodeProj

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

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

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

javascript




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: Database

Console Output:

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

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.



Last Updated : 15 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads