I wonder, what is Mongoose's isModified function actually verifying?

I have come across this specific isModified check frequently while researching, and even after reviewing Mongoose's documentation, I still struggle to grasp its precise purpose or significance.

Initially, I considered the possibility that the check was related to a user resetting their password, with the intention of verifying if the "new password" matched the "db password." However, this theory doesn't hold up because passwords are typically stored as hashes. Now, I find myself unsure of the true reason behind this conditional statement.

schema.pre("save", async function(next) {

  if (!this.isModified("password")) {
    return next();
  }


  try {
    const salt = await bcrypt.genSalt(10);
    let hashedPassword = await bcrypt.hash(this.password, salt);
    this.password = hashedPassword;
    return next();
  } catch (error) {
    return next(error);
  }
});

Answer №1

It checks for any changes in the path and returns a true or false value. The example provided demonstrates that this only works if you make modifications to the mongoose object using the set method, as it does not work with UpdateOne or UpdateMany. More information can be found at https://mongoosejs.com/docs/api/document.html#document_Document-isModified

Utilizing your presave hook:

let doc = await model.FindOne({})
doc.set("username", "john")
doc.save() // isModified('password') returns false


doc.set("password", "newpassword")
doc.save() // isModified('password') returns true

In your presave hook, it checks if a new password has been set, then hashes the password and updates the password field with the hashed value.

For instance:

doc.set("password", "newpassword")
doc.save()

You will notice that a random hash is stored in the password field instead of "newpassword"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a rectangular pyramid using three.js r68: a step-by-step guide

Currently working on r68, I'm in search of a modern example showcasing the creation of a rectangular pyramid that will allow me to implement THREE.MeshFaceMaterial(). Many existing examples are outdated and lead to errors with my current setup. My re ...

Is the IE7 Modal Dialog Misaligned?

Update After some investigation, I discovered the root cause of the problem. In my code, I was referencing the height of the overlay, which resulted in different values in IE7 compared to other browsers. To resolve this issue, I adjusted the code to refe ...

Retrieving values with Jquery on a function's onClick event

Here is a small script that retrieves values from a select element <script> jQuery(document).ready(function() { var selectedValue = jQuery("#tr_val").val(); }); </script> When you click on this div and execute the open_win function, I need t ...

Consider creating a distinct document for your "scripts"

Within my package.json configuration file, the "scripts" section contains numerous commands structured as shown below. "scripts" { "script1": "command example", "script2": "command example", "script3": "command example", "script4": "command exampl ...

The issue of asynchronous nested callbacks not functioning properly within each iteration of a for loop in Node.js

I have been using the code snippets below to retrieve followers of a specific user stored in mongodb. Here is an example of a saved user JSON: { "_id":{ "$oid":"5440f606255cd4740e88ed21" }, "username":"test2", "email":"test2%40gmail.com", " ...

Error: The TVJS Framework encountered a JSON Parse issue due to an unexpected EOF

I am currently developing a TVML application specifically for Apple TV. However, when I attempt to execute this code to send a request to a remote server, I encounter the following error: SyntaxError: JSON Parse error: Unexpected EOF. My goal is to run thi ...

Enhance data granularity in Jquery Flot by zooming in as the user interacts

I'm currently working on creating an interactive chart that allows users to zoom in for a more detailed view of the data. For instance, when viewing data over a default zoom period of 3 months, there would be one data point displayed every 24 hours. H ...

Converting Plain JSON Objects into a Hierarchical Folder Structure using Logic

Looking at the data provided below: [ {name: 'SubFolder1', parent: 'Folder1'}, {name: 'SubFolder2', parent: 'SubFolder1'}, {name: 'SubFolder3', parent: 'SubFolder2'}, {name: 'Document ...

Instructions for transforming DOM information into a JSON format

I have multiple inputs within my document, as shown in the code snippet below. My goal is to create a string or JSON object using the input names and values. var arr= []; $('ul li input').each(function(){ let name = $(this).attr(' ...

What is the best way to use React to display all user post images on a webpage in real

I'm currently working on a React web application where I want to display images in all user posts on my Discover component. The JSON objects look like this: https://i.stack.imgur.com/ZM6Lu.png This is the current state of my discover component. Dis ...

Rows intersecting and stacking above one another

I designed a layout with some text and icons displayed in rows. While it appears properly on iOS, the rows overlap on Android. const criteriaList = [ { id: 0, title: 'Noor', checked: false }, { id: 1, title: 'Friends & Grades', ...

I need to send information from my JavaScript code to my Flask server

I'm having an issue with transferring data from JavaScript code in an HTML template to my Flask server. Specifically, I want to send geolocation coordinates (latitude and longitude) obtained through JavaScript to my Flask server, but I'm unsure o ...

Experiencing slow loading times with a Next.js app in the development environment

Currently, I am in the process of building a Next.js application and I have noticed that it takes quite a long time to load in the development environment. At the start, the page becomes unresponsive and if I cancel the request, it stops loading altogeth ...

The React component is experiencing a delay in its updates

I've been experiencing delayed updates when using React.useEffect(). Can anyone shed some light on why this might be happening? function Process(props) { const [results, setResults] = React.useState({ number: "", f: {} }); let ...

The implementation of gulp-less encounters issues when the !important rule is applied

When the !important declaration is used on a specific less variable, it causes the build to fail. The use of !important is common in our codebase, so it's puzzling why this particular instance is causing an issue. Setup: customer1.less @import "bas ...

Navigating the Angular Element: A Guide to Clicking Buttons within Modal-Dialogs Using Protractor

I am currently creating an automation test for an angular application using the protractor framework. Test scenario: Click on the "Create PDF Report" button A modal-dialog window will appear Click on the "Run Report Now" button within the modal-d ...

Is it possible to transfer a child from one parent to another using JavaScript?

I need help with moving an element from one parent to another using JavaScript, preferably using the jQuery library. Original code: <div id = "div1"> <p id = "paragraph"> Lorem ipsum dolor sit amet, adipiscing pellentesque egestas. &l ...

Attempting to loop through nested dictionaries within a pymongo database

I am currently facing a challenge in iterating over a MongoDB collection that contains nested subdictionaries. Within the structure of my collection, there is an object that holds other string values: For example: My goal is to retrieve the stats from t ...

Why is it that when I search for my role by name, it comes back as

const checkGang = (message) => { Gang.findOne({ leaderUserID: message.author.id, leaderUserName: message.member.user.tag, serverID: message.guild.id }, (err, gang) => { if(err) console.log(err); ...

"Trouble with props: List items not showing up after refreshing the page

I am facing an issue with my "Event Selector" component where it is not displaying the list items as expected. The component is supposed to create a button for each item in the 'lists' passed via props. Strangely, the items do not show up upon re ...