The document is not being updated by Mongoose's findByIdAndUpdate function

Struggling to use Mongoose findByIdAndUpdate for updating a document by ID, the operation runs smoothly but changes are not reflected in the database.

In the server log, I only see users.findOne being logged when I trigger the API. Shouldn't Mongoose also execute the update along with it? Creating and deleting users works fine without any issues.

Interface

export interface User {
  _id: string;
  email: string;
  password: string;
}

Model

const userSchema: Schema = new Schema({
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
});

Controller

public updateUser = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const userId: string = req.params.id;
      const userData: CreateUserDto = req.body;
      const updateUserData: User = await this.userService.updateUser(userId, userData);

      res.status(200).json({ data: updateUserData, message: 'updated' });
    } catch (error) {
      next(error);
    }
  };

Service

  public async updateUser(userId: string, userData: CreateUserDto): Promise<User> {
    if (isEmpty(userData)) throw new HttpException(400, "You're missing userData");

    if (userData.email) {
      const findUser: User = await this.users.findOne({ email: userData.email });
      if (findUser && findUser._id != userId) throw new HttpException(409, `The email ${userData.email} is already in use`);
    }

    if (userData.password) {
      const hashedPassword = await bcrypt.hash(userData.password, 10);
      userData = { ...userData, password: hashedPassword };
    }

    const updatedUser: User = await this.users.findOneAndUpdate({ _id: userId }, { userData }, { new: true });
    if (!updatedUser) throw new HttpException(409, "User not found");

    return updatedUser;
  }

Dtos

import { IsEmail, IsString } from 'class-validator';

export class CreateUserDto {
  @IsEmail()
  public email: string;

  @IsString()
  public password: string;
}

Logs when running the update API

mongodbexpress | {"t":{"$date":"2021-08-23T05:19:26.698+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"Checkpointer","msg":"WiredTiger message","attr":{"message":"[1629695966:698802][1:0x7f5f10065700], WT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 664, snapshot max: 664 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 2092"}}
server    | Mongoose: users.findOne({ email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="17797260720e7b397478">[email protected]</a>' }, { projection: {} })
server    | Mongoose: users.findOne({ _id: ObjectId("6122ae51d922ae0a85b85484") }, { new: true, projection: {} })
server    | 2021-08-23 05:19:27 info: PUT /users/6122ae51d922ae0a85b85484 200 75.025 ms - 

Answer №1

Your update operation is failing because you are passing { userData } as the update parameter to findOneAndUpdate(). This is equivalent to { userData: userData } which does not align with your schema requirements. To fix this issue, simply make a small adjustment:

const updatedUser: User = await this.users.findOneAndUpdate({ _id: userId }, userData, { new: true });

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

modify the username in the Mongoose data model

I am looking to provide users with the ability to update their usernames in the mondgod database. My database is set up using mongoose as ODM, and here is the schema for my user: UserSchema = new mongoose.Schema({ username: String, phone: { ...

Encountering a problem: React is returning null when utilizing JavaScript import maps to bring in a project to an already existing project

I am in the process of developing Project A, which focuses on creating reusable components through Vite. The main objective is to export these components to other projects that already exist. In order to accomplish this task, I have employed JavaScript imp ...

Parsing POST requests in Express.js from an Angular 2 application

I am currently encountering an issue with my Node.js code: app.post('/register', function(req, res) { console.log(req.body); It seems that the req object does not contain the body property. When using Angular2, I am sending stringified JSON ...

The program encountered an error stating that "Articles" is not defined

Two schemas are defined in my program. The first one works perfectly: var mongoose = require('mongoose'), Schema = mongoose.Schema; var NewsSchema = new Schema({ name: String, route: String, remoteURL: String, artic ...

Building Custom Request Types for a Personalized Express Router in TypeScript (TS2769)

I've been facing challenges integrating custom Request types with TypeScript. Within my application, I have both public and private routes. The public routes utilize the Request type from Express. On the other hand, the private routes make use of a ...

Is it possible to incorporate variables when updating an array or nested document in a mongodb operation?

Within the "myCollection" target collection, there exists a field named "japanese2". This field is an array or an object that contains another object with a property called "japanese2a", initially set to 0 but subject to change. My goal is to update this p ...

How can I utilize inline jade.render() in Express with Jade template engine?

I am facing a challenge while attempting to utilize another team's jade template with Node's Jade. The template is quite intricate, featuring numerous mixins and other components. I have encountered an issue within one of the mixins that prevents ...

What is the Axios counterpart to req.pipe(request()) / Transferring data from an Express request into an Axios request via piping

When using the request package, you have the ability to send a POST multipart/form-data request from express to another server without altering the body or parameters of the initial request, and then receive the response back in express. However, this feat ...

You cannot use the "this" keyword outside of a class body

I am facing an issue with my function, can someone help me? Here is the code: function remove_multi_leg(): void { if (Number($("#search_no_legs").val()) < 2) { return; } const removeId: number = Number($(this).attr("data-number")); const ...

AngularJS session timeout refers to the period of inactivity before

Would it be possible to handle user sessions with Angularjs? For example: Setting session timeout for idle systems. Displaying alerts (popup with message asking if the user wants to continue - yes or no) when the session is about to expire, with the optio ...

Building a versatile setting within a child component by incorporating TypeScript and deriving state data from the parent component

In my page component, I have set a state called formData. Now, I want to create a context within my form component so that I can utilize it in each child form component. Everything works smoothly without TypeScript. However, when using TypeScript, I encoun ...

Using React Router and Flux for automated redirection in a programmatic manner

Currently immersed in a project leveraging NodeJS, Express, Flux and React, with the added use of React Router for client-side routing. It appears I might be misunderstanding how the process should ideally function. My present goal is to redirect users to ...

Modifying intricately nested arrays in MongoDB

How can I add a value to the attachments array in MongoDB using an update query with specific criteria? The criteria for the update query are as follows: _id: ObjectId("5b56bd2f3e18580edc85af73") cardID: ObjectId("5b56c895d0a04836f71aa776") commentId: "2 ...

mat-tab-group - Positions elements in the center, right, and left for optimal alignment

Is it possible to align the buttons in a mat-tab-group to the left, center, and right positions? I am using mat-tabs. How can I have elements with "left" align to the left, elements with "center" in the center, and elements with "right" align to the right? ...

Querying across multiple collections in MongoDB is a powerful feature that allows users

Within my database, I have an Application collection that contains documents in the following format: { "_id" : "TAIS", "commonUserName" : "TAIS", "scopes" : [ DBRef("Scope", "GEN_ECO"), DBRef("Scope", "GEN_PRE") ] } The d ...

Switching Theme Dynamically in a Multi-tenant Next.js + Tailwind App

I'm currently developing a Next.js + Tailwind application that supports multiple tenants and allows each tenant to easily switch styles or themes. I've been struggling with the idea of how to implement this feature without requiring a rebuild of ...

Utilizing the adapter design pattern in Angular with TypeScript for enhancing a reactive form implementation

I've been struggling to understand how to implement the adapter pattern in Angular6. Despite reading numerous articles and tutorials, I still can't quite grasp the concept. Could someone provide some insights on this topic? Essentially, I have a ...

When building websites, pages, or applications with React, how do you determine the best choice between JavaScript, TypeScript, or JavaScriptXML?

After completing my portfolio and an eCommerce website design using Figma, I started learning React and Tailwind with Vite. I'm comfortable with basic JavaScript but now I want to understand the differences between .js, .jsx, and .ts files when workin ...

When you click on one checkbox, the angular2-multiselect dropdown automatically selects all the boxes

<angular2-multiselect [data]="sortedDataList | OrderBy : 'clientName'" [(ngModel)]="selectedItem[sortedDataList.clientId]" [settings]="dropdownSettings" name="multiSelect" (onSelect)="onItemSelect($event, ...

Unable to alter the input data within the LCJS chart

I have been utilizing LightningChart JS to create scrolling line charts. After following an official tutorial by the developers on YouTube, I was able to successfully implement the automatic generated data. Now, I am looking to modify the input to a JSON f ...