findByIdAndUpdate() function

Aditya kumar
Last Updated: May 13, 2022

Introduction

Mongoose is a library for MongoDB and Node.js. In simple terms, it establishes the connection between our Node.js backend code to the MongoDB database. It makes the life of the developer easier as it exposes lots of functions that are helpful in performing any type of CRUD(Create Read Update Delete) operations to the database directly from our backend code. One of the functions is findByIdAndUpdate() which is really helpful in performing update operations in a database. Of course, there are lots of update functions available in a Mongoose library for updating data in a database but findByIdAndUpdate() is mostly used because of its simplicity and flexibility.

 

We know in MongoDB every document has its own unique auto-generated _id field. This id is passed inside the findByIdAndUpdate() function and then it simply grabs the document matching that particular id. After getting the document with that matching id, it simply updates the data inside the document. What needs to be updated inside the document is specified in the function as an argument.

 

Working with findByIdAndUpdate()

Before working with this function, you need to first install the Mongoose library. You can install it from its official site: Install mongoose. Or just type this command to install it:npm install mongoose

 

After installing, check the package.json file, it will be present there with its version.

 

package.json file:

{

  "dependencies": {

    "mongoose""^6.0.13"

  }

}

 

Now, make a script.js file where we work on the database using the mongoose library. Your file structure will look like this,

 

 

Now our project is set but before working on the database we have to create the database. I’m using MongoDB Compass to create a database. I’m creating the ‘blog’ database with the ‘users’ collection and this collection has 3 documents. After creating the database, it will look like this,

 

 

Now, let’s connect this database to our backend code and update the data using the findByIdAndUpdate() function. We want to update the user “Mia Dames” profession from “Frontend Developer” to “Backend Developer”. For that, we have to pass her id and update parameter to the function. Remember these two arguments are compulsory.

 

script.js file:

const mongoose = require("mongoose");

mongoose
  .connect("mongodb://localhost:27017/blog", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => console.log("connection successful...."))
  .catch((err) => console.error(err));

const usersSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  profession: String,
  age: Number,
  dateOfJoining: {
    type: Date,
    default: Date.now,
  },
});

const User = new mongoose.model("User",  usersSchema);

const updateDocument = async (id) => {
  try {
    const updatedResult = await User.findByIdAndUpdate(
      { _id: id },
      {
        profession: "Backend Developer",
      },
    );
    console.log(updatedResult);
  } catch (error) {
    console.log(error);
  }
};

updateDocument("61993cf5f39ba26a984b480f");

 

Analysing the code above, we first established the connection to our “blog” database then we defined and modelled the schema for our “users” collection in the blog database. We then defined an asynchronous function updateDcoument using async/await which takes the id of the user to perform an update operation. We made this asynchronous because update operation takes time to complete and we don’t want to block the rest of the code because of this.

 

Inside updateDocument function, we used findByIdAndUpdate() function and passed-in the id and the update parameter to perform update operation. We’ve put these inside try/catch block so that if this operation is failed then an error will be caught.

 

Now, run the script.js file inside the terminal by typing this command,

 

node script.js 

 

Output:

 

The output shows everything unchanged. We performed an update operation but it is not reflected in the output when we console.log() the result. Well, it is because the findByIdAndUpdate() function returns the matching document first and then performs the update operation. It is not reflected in the output but when we look at the database in the MongoDB Compass, you’ll see the changes in the document there. 

 

See below, there is a change in the profession of the user. Previously it was “Frontend Developer” now it changed to “Backend Developer”.

 

To make the changes to reflect in the console also, pass the third argument inside findByIdAndUpdate() function as an object and set,

 

  new: true

 

Now, let’s say this time we want to change the profession from “Backend Developer” to “full-stack Developer”.

 

const updateDocument = async (id) => {
  try {
    const updatedResult = await User.findByIdAndUpdate(
      { _id: id },
      {
        profession: "full-stack Developer",
      },
      {
        new: true,
      }
    );
    console.log(updatedResult);
  } catch (error) {
    console.log(error);
  }
};

 

See the output below, the changes are reflected inside both console and MongoDB Compass.

 

Output:

 

 

Upserting data

What if we pass the wrong id to findByIdAndUpdate() function? Well, nothing happens as it won’t find any matching document. But there is an option by using which we can utilize this situation to our advantage.

 

Suppose, we want to add a new document if the value of the _id field does not match. We can use the upsert option. The upsert option will add a new document and this new document will contain the content of the update that was passed to the findByIdAndUpdate() function.

 

For using this functionality, just set upsert: true

 

const updateDocument = async (id) => {
  try {
    const updatedResult = await User.findByIdAndUpdate(
      { _id: id },
      {
        profession: "full-stack Developer",
      },
      {
        new: true,
        upsert: true,
      }
    );
    console.log(updatedResult);
  } catch (error) {
    console.log(error);
  }
};

updateDocument("61997cf5f69ba26a984b480f");

 

See, here we have specified a wrong id that doesn’t match any document inside the database.

 

updateDocument("61997cf5f69ba26a984b480f");

 

See the output below, a new document is created if it doesn’t find the matching id.

 

Output:

 

 

Frequently asked questions

  1. For what purpose findByIdAndUpdate() function is used for?
    This function is used for performing the update operation to our database by making use of the id of the particular document. This function mainly takes 2 compulsory arguments, the first one is the id and the second one is the actual update data.
     
  2. Why are the changes not reflected in the document when we console.log the result?
    This is because the findByIdAndUpdate() function returns that matched document first and then performs the update operation.
     
  3. What do you mean by upserting data when using the findByIdAndUpdate() function?
    When the findByIdAndUpdate() function doesn't find the matching document based on the id passed inside of it, then it simply adds or creates a new document based on that id inside the database. For this thing to happen, we have to pass the third argument an object and set upsert: true.

 

Key takeaways

So, finally, we've reached the end. As mentioned earlier, there are many functions for updating data in MongoDB, but findByIdAndUpdate() is mostly used. The value of the _id field is always unique in a collection, and there is no margin of error when we use the findByIdAndUpdate() method.

You can learn about practical implementation of mongoDB from here My first express app. And if you want to learn about mongoDb commands which are frequently used then you can learn here 25 Most Common Commands for MongoDB Beginners.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think