The functions isModified and isNew in Mongoose

In various tutorials, I have come across this particular example and it has raised a question in my mind. I am curious as to why this works with new documents. Could it be that new documents are automatically considered modified? Wouldn't it make more sense to use this.isNew || this.isModified instead of just isModified?


  try {
      if (!this.isModified("password")) {
        return next();
      }
      let hashedPassword = await bcrypt.hash(this.password, 10);
      this.password = hashedPassword;
      return next();
  } catch (err) {
      return next(err);
 }
});

Answer №1

The explanation on this topic is quite ambiguous, therefore, let's gain understanding through practical experimentation:

schema.pre("save", async function(next) {
  console.log("password isModified: ", this.isModified("password"));
  console.log("isNew: ", this.isNew);
  next();
});

Upon creating a new user, the resulting output would appear as follows:

password isModified:  true
isNew:  true

From this, we can observe that the this.isModified("password") is indeed true. Hence, we can deduce that this.isModified("password") also holds true for freshly added documents.

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

problem decoding json data from external server

I have a custom Grease Monkey script that is responsible for collecting data from a game and sending it to my server for tracking our team's progress. This process involves multiple Ajax requests between the GM script and the game, followed by sending ...

How can permissions for video and audio be configured in Next.js?

When the button is clicked, I want to set permissions. This is how I'd like the scenario to play out: first, the method works initially and allows permission when the button is pressed. Here is my code: <button onClick={requestPermission} classN ...

Why is it that when drawing rectangles with HTML 5 canvas using pixel size, a black rectangle appears instead of blue?

My intention was to create a large blue rectangle measuring 320 X 240 pixels on the Canvas in Firefox, but I'm only getting a black rectangle instead. This issue is perplexing as I am simply experimenting with pixel drawing and for some reason, it&apo ...

Retrieve an array of 16 elements using React in a TypeScript environment

Exploring the new React 16 feature to return array elements within the render method is throwing a TypeScript error stating "Property 'type' is missing in type 'Element[]'" const Elements: StatelessComponent<{}> = () => ([ & ...

Error: The function gethostname has not been declared

I attempted to set a variable using gethostname() (1) and with $_SERVER(2), but I always receive an error message saying ReferenceError: gethostname is not defined. My goal is simply to fetch the current system name into a variable using JavaScript within ...

Seeking a sleeker approach to composing various components with shared functions

Currently, I have a scenario where I have identical components that display data but also need to handle state manipulation and saving. There are 5 other similar components with slight differences in their functions. I am looking for a more efficient way t ...

I'm just starting out with jQuery and JSON and could use some assistance with formatting the string, specifically so I can properly iterate through it

This is the controller. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> @RequestMapping("/getDropDownAjax") public void fetchData(HttpServletRequest req,HttpServletResponse resp){ System.out.println ...

What is the best method for determining values within JSON data?

In my possession is a JSON file containing user data that looks like this: [ { "id": 0, "username": "Antony", "users": [ { "id& ...

Exploring the functionalities of JavaScript methods and nested components within Vue.js

Learning Vue.js has been an interesting experience for me. However, I am facing challenges with methods and child elements in the library. It seems like there is something simple that I am overlooking. In my current project, I have list items rendered on ...

Utilizing jQuery time intervals within a jQuery click event: A step-by-step guide

For my dropdown menu project, I am facing an issue where the menu bar is not reappearing after collapsing the dropdown. It seems that the jQuery function responsible for toggling classes within a time interval is not executing properly. Specifically, the " ...

The JQuery function .remove() will not properly remove dynamically added elements

I am facing an issue when trying to remove an element from a page. Every time I click on a button on the page, it adds a div with the following structure: <div class="holder-div" style="position: relative;display: inline-block;"> ...

Can you retrieve all population data using Mongoose by specifying IDs?

Seeking assistance with creating a query in my API endpoint that retrieves all documents and subdocuments. Currently, I am able to fetch only the IDs of each subdocument instead of obtaining all the information within each document. Is there a way to extra ...

Decline the input according to the percentage

After experimenting with the script, I discovered that it did not perform as expected (even though it works on Google Webapp's script HTML form). My goal is to invalidate an input if the Downpayment is less than 30% or more than 100% of the Price, in ...

Jquery for controlling the navigation menu

I'm new to JavaScript and facing 3 challenges: 1. When I click on the parent <li>, the correct content of the child <sub> does not show up. Each category like "colors, shapes, sizes" should have corresponding child categories like "green, ...

Tips for dynamically loading images in React with a Collage component

It appears that all the examples I've come across are static in terms of loading images. While the code works, it does not display the divider <div> tag as expected. Instead, the results (images) are shown stacked in the first item of the Collag ...

Manage the material-ui slider using play and pause buttons in a React JS application

I have a ReactJS project where I am utilizing the continuous slider component from material-ui. My goal is to be able to control the slider's movement by clicking on a play button to start it and stop button to halt it. Below is the code snippet of th ...

Tips for updating the css class for multiple DOM elements using jQuery

I am currently attempting to modify the class property of a specific DOM element (in this case, a label tag) using jQuery version 1.10.2. Here is the code snippet I have written: var MyNameSpace = MyNameSpace || {}; MyNameSpace.enableDisableLabels = (f ...

"Ensuring Security with Stripe Connect: Addressing Content Security Policy Challenges

Despite using meta tags to address it, the error persists and the Iframe remains non-functional. <meta http-equiv="Content-Security-Policy" content=" default-src *; style-src 'self' 'unsafe-inline'; ...

Maximizing efficiency in Office Automation programming by choosing individuals proficient in Javascript and PHP

I am seeking a solution where upon selecting a department checkbox, the employees belonging to that department will be displayed in the second div. This way, I can easily select an employee and have their information displayed in a separate section. I al ...

Implementing a New Port Number on a ReactJs Local Server Every Time

As a newcomer to ReactJS, I recently encountered an issue while working on a project that puzzled me. Every time I shut down my local server and try to relaunch the app in the browser using npm start, it fails to restart on the same port. Instead, I have ...