Open In App

Mongoose Queries Model.findByIdAndUpdate() Function

Last Updated : 21 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The Mongoose Queries findByIdAndUpdate() function is used to search for a matching document, update it in accordance with the update argument while giving any options, then return the found document (if any) to the callback.

Installation of Mongoose Module:

Step 1. You can visit the link to Install the mongoose module. You can install this package by using this command.

npm install mongoose

Step 2. You may use the command to check your mongoose version at the command prompt after installing the module.

npm version mongoose

Step 3. Following that, you can simply make a folder and include a file, like index.js. You must perform the following command in order to run this file.

node index.js

Syntax:

Model.findByIdAndUpdate(id, update, options, callback)

Parameters: This method accepts four parameters as mentioned above and described below.

  • id: Finding the documents that match a given Id. This can be in an Object, Number, or String.
  • update: In this parameter, we pass an object with an updated value that we want to update in our database.
  • options: There are multiple options available for different purposes.
    • returnDocument:  This is a String type option. It can have either a “before” or an “after” value. It will by default return the document from before the modification was made.
    • lean: This is an Object type option. Instead of returning the document as a mongoose document, Mongoose will do so as a simple JavaScript object.
    • session: This is a Client Session type option. Using to associate the session with this query. The default value is null.
    • strict: This can be a boolean or string type option. It overrides the strict mode setting in the schema.
    • timestamps:  This is a boolean-type option. If the value is false and timestamps at the schema level are enabled, this update will not include timestamps. Keep in mind that we can overwrite timestamps using this. If schema-level timestamps are not set, nothing happens. Null is the default value.
    • overwrite: This is a boolean-type option. The default value is false. By default, Mongoose will wrap the update in $set for us if you don’t include any update operators in the update. This stops us from unintentionally overwriting the file. By selecting this, Mongoose is instructed to omit the $set.
    • sort: This can be an Object or string type option. To decide which document to update, it establishes the sort order.
    • runValidators: This is a boolean-type option. Runs update validators on this command if true. Update validators examine the model’s schema to verify the update process.
    • setDefaultsOnInsert: This is a boolean-type option. When a new document is created, mongoose will use the defaults supplied in the model’s schema if setDefaultsOnInsert and upsert are both set to true.
    • rawResult: This is a boolean-type option. This is a boolean-type option. If true, the MongoDB driver’s raw result is returned.
    • upsert:  This is a boolean-type option. If true, and no documents are found, insert a new document.
    • new: This is a boolean-type option. If true, return the modified document rather than the original.
    • select: This can be an Object or string type option. It sets the document fields to return.
  • callback: This is a callback function that will be executed once our query gets executed successfully.  This is an optional parameter. 

Project Structure: 

Project Structure

Our project is now ready, but we must first establish the database before we can work on it. We are building a database with MongoDB Compass. The “employee” collection, which we are using to create the “gfg” database, contains three documents. This is how the database will seem when it has been created:

 

Example 1: In this example, We are discussing the use of the {new: true} option parameter and showing the differences in the results with or without this argument in the findByIdAndUpdate function.

Filename: index.js 

Javascript




const mongoose = require("mongoose");
  
mongoose
    .connect("mongodb://localhost:27017/gfg", {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })
    .then(() => console.log("Successfully Connected"))
    .catch((err) => console.error(err));
  
const employeeSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    designation: {
        type: String,
        default: "",
    },
    age: {
        type: Number,
        default: 0,
    },
    dateOfJoining: {
        type: Date,
        default: Date.now,
    },
});
  
const Employee = new mongoose.model("Employee", employeeSchema);
  
const updateDocument = async (id) => {
    try {
        const updatedResult =
            await Employee.findByIdAndUpdate(
                { _id: id },
                {
                    designation: "Software Engineer",
                    age: 25
                }
            );
        console.log(updatedResult);
    } catch (error) {
        console.log(error);
    }
};
  
updateDocument("61993cf5f39ba26a984b480f");


After establishing the connection to our “gfg” database, we constructed and modeled the schema for our “employees” collection in the gfg database. Then, using async/await, we built the asynchronous function updateDcoument, which requires the employee’s ID to carry out an update operation. We created this asynchronous since updating an object takes some time, and we didn’t want the rest of the function to be blocked while updating an object.

The id and the update parameter were passed to the findByIdAndUpdate() function inside the updateDocument function to carry out the update operation. These are contained within a try/catch block so that an error will be caught if the operation fails. 

Run the index.js file using the below command:

node index.js

 

The results showed that nothing has changed. When we console.log() the result, the updated data is not reflected in the console. It’s because the findByIdAndUpdate() function updates the document after returning the matching document first. The changes to the document are visible in the database while using MongoDB Compass, but they are not reflected in the output.

After the function is executed, We can see in the database that the particular employee data is updated as shown below:

 

If we want to print or reflect the updated data in the console, then we need to insert a third options parameter inside the findByIdAndUpdate function. We need to replace the previous updateDocument method with the below new one for reflecting the updated document in the console.

Javascript




const updateDocument = async (id) => {
    try {
        const updatedResult = await Employee.findByIdAndUpdate(
            { _id: id },
            {
                designation: "Software Engineer",
                age: 25
            },
            {
                new: true
            }
        );
        console.log(updatedResult);
    } catch (error) {
        console.log(error);
    }
};


Now, We will able to see the updated document data in the console also. 

 

Example 2: In this example, we are discussing the situation if the user given _id does match any document id what will happen and how to tackle that situation.

Let us suppose, we will give any document id which does not exist in our collection and if we tried to perform the update operation, then nothing will happen or no documents will get updated. But, We want to add a new document when the document id does not exist in the collection. Then, we can use our next option parameter named upsert. We need to pass the {upsert: true} in the options argument. Like this below-given code:

Filename: index.js 

Javascript




const mongoose = require("mongoose");
  
mongoose
    .connect("mongodb://localhost:27017/gfg", {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })
    .then(() => console.log("Successfully Connected"))
    .catch((err) => console.error(err));
  
const employeeSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    designation: {
        type: String,
        default: "",
    },
    age: {
        type: Number,
        default: 0,
    },
    dateOfJoining: {
        type: Date,
        default: Date.now,
    },
});
  
const Employee =
    new mongoose.model("Employee", employeeSchema);
  
const updateDocument = async (id) => {
    try {
        const updatedResult = 
            await Employee.findByIdAndUpdate(
            { _id: id },
            {
                designation: "Software Engineer",
                age: 25
            },
            {
                new: true,
                upsert: true,
            }
        );
        console.log(updatedResult);
    } catch (error) {
        console.log(error);
    }
};
  
updateDocument("639769ca25e1f3b5a58843b3");


Output:

 

Reference: https://mongoosejs.com/docs/api.html#model_Model-findByIdAndUpdate



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads