When using mongoose.save(), the data is not stored successfully

I spent 5 hours trying to solve this problem but couldn't figure out what's wrong

in the file -routes/users.ts,

The line ""targetUser.token = token" is working, so console.log(targetUser) shows the updated user data.

However, targetUser.save() is not updating this data in MONGO DB... why is that?

-User.ts-

import mongoose, { Document, Schema } from "mongoose";
import bcrypt from "bcrypt";

const saltRounds = 10;

const userSchema = new Schema({
 name: {
   type: String,
   maxlength: 50,
 },
 email: {
   type: String,
   trim: true,
   unique: 1,
 },
 password: {
   type: String,
   minlength: 5,
 },
 lastname: {
   type: String,
   maxlength: 50,
 }, 
 // Rest of the schema properties...

export interface UserBaseDocumentType extends Document {
 name: string;
 email: string;
 password: string;
 lastname: string;
 role: number;
 art: [];
 history: [];
 image: string;
 token: string;
 tokenExp: string;
 comparePassword(plainPassword: string): Promise<boolean>;
}

// Code for pre-save middleware and methods...

///////////////export this model////////////////////////////
export default mongoose.model<UserBaseDocumentType>("User", userSchema);
///////////////////////////////////////////

-index.ts-

import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import mongoose from "mongoose";
const mongoDBAccessKey = require("./config/key");
import userRouter from "./routes/users";

// App initialization and setting up middlewares...

// MongoDB connection setup...

// Routes setup...

// Port configuration and server start...

It seems like TypeScript doesn't recognize mongoose's Document type, causing issues with the save() method. Any help would be greatly appreciated.

Answer №1

It seems like the issue lies within your pre-save middleware. Upon closer inspection, you'll notice that the next() function is only called if the updates include the password field. If the update object does not contain this field, the middleware will prevent the save method from being executed because next() was never invoked. To verify if this is indeed the problem, try adding next() for all updates, even those that do not involve the password:

userSchema.pre<UserBaseDocumentType>("save", function (next) {
 let user = this;
 if (user.isModified("password")) {
   bcrypt.genSalt(saltRounds, function (err, salt) {
     if (err) return next(err);
     bcrypt.hash(user.password, salt, function (err, hash) {
       if (err) return next(err);
       user.password = hash;
       next();
     });
   });
 }
 next();
});

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

Determine whether Express Sequelize returns a boolean value of true or false

Currently, I am working on validating user access levels to authorize certain actions within the service. exports.hasAdminAccess = function(req, res, next) { if (hasAccessLevel(req.user, adminLevel)) { return next() } res.redirect('/accessP ...

"Problems arise with mongodb full $text search when sorting and filtering, causing duplicate items to

When using full-text search in my API and sorting by score, I am encountering an issue where the same item is returned multiple times. This behavior is not what I expected. How can I correct this to ensure unique results? Below is the structure of my rout ...

The CORS policy has blocked the 'Access-Control-Allow-Origin' header

My expertise lies in creating API, BackEnd, and Frontend websites. For the API, I utilize Express, while for the BackEnd - FrontEnd, I rely on ReactJs. During local testing, everything functions as expected. However, upon deployment to the server, error ...

TS type defined by JS constants

I am currently working on a project that involves both JavaScript and TypeScript. I am trying to find a solution to reduce code duplication when using JavaScript string constants by converting them into TypeScript types. For example, let's say I have ...

Using data retrieved from a JSON response to make HTTP requests in a recursive manner

I am in the process of extracting all names from an API that provides a JSON response structured like this: { "data" : [ { "attributes" : { "name" : "Prog1" ... ...

Tips for presenting JSON data in a tabular format using node.js

Hey there! I've been working on creating a table using my mongo database. My initial idea was to loop through the data and display it, but I'm not quite sure how to do that in node.js. Below is the code I have so far: var express = require(&apos ...

Passing a retrieved parameter from the URL into a nested component in Angular

I'm currently facing an issue where I am trying to extract a value from the URL and inject it into a child component. While I can successfully retrieve the parameter from the URL and update my DOM with a property, the behavior changes when I attempt t ...

Is there a way to create a stub for the given function using sinon?

Here is my test function: const customTestLibrary = require("./test"); describe("Initial Test", function() { it("should run the test function successfully", function(done) { customTestLibrary.execute(); done(); }); }); The te ...

Issue: Unable to find suitable routes for navigation. URL Segment: 'profile' or Encounter: Server could not load resource as response status is 401 (Unauthorized)

Currently, I am working on the MEANAUTH application and encountering an issue with accessing user profiles using angular jwt. When attempting to log in and access user profiles at https://localhost:3000/profile, I receive the following error message: Faile ...

Quick + Vue Router - Lazy Loading Modules

For my personal project, I am using Vite alongside Vue 3 and have integrated vue-router@4 for managing routes. Since all of my modules share the same set of routes, I created a helper function: import { RouteRecordRaw } from 'vue-router' import p ...

When using res.render to pass data to an EJS file and accessing it in plain JavaScript

I'm currently working on an Express GET function where I am sending data to an EJS file using the res.render() function. My question is, how can I access this data in plain JavaScript within the same EJS file? Here is my GET Function: router.get(&a ...

Using Typescript with Nuxt can become tricky when attempting to inject data into `Vue.extend` as it appears to be

I want to implement TypeScript support in my Nuxt project. From my understanding, I need to use Vue.extend when returning the component data like this: import Vue from 'vue'; type Data = { a: number } export default Vue.extend({ data():Data{ ...

The implementation of CommonJS modules allows for efficient modularization

While using Nx for my Angular workspace, I noticed something that sparked a question in my mind. Why is it necessary to use CommonJS modules in all tsconfig.spec.json files for libs? Looking at Nx examples, I observed that not all libs include it, only app ...

The Order ID field in the Serenity-Platform's Order Details tab is not registering orders

I've been working on replicating the functionality of Orders-Order detail in my own project. https://i.stack.imgur.com/Bt47B.png My custom module is called Contract and Contract Line item, which I'm using to achieve this. https://i.stack.imgur ...

What is the best way to handle parameters in express routes?

I've been stuck on a simple question for the past two days while learning NodeJs. I'm encountering an issue that I haven't faced in my development environment, which is quite confusing. In my server.js, I have defined two routes: const gove ...

Enhance your TypeScript classes with decorators that can add new methods to your class

Can you explain property definition using TypeScript and decorators? Let's take a look at this class decorator: function Entity<TFunction extends Function>(target: TFunction): TFunction { Object.defineProperty(target.prototype, 'test& ...

Are your custom guards failing to function properly now?

Previously, the code below was functioning properly until typescript 2.0: class Aluno{ escola: string; constructor(public nome: string){ this.escola = ""; } } class Pessoa{ morada: string; constructor(public nome: string){ this.morada = ...

Getting a specific array from the API with fetch in Angular: A step-by-step guide

I am trying to retrieve images from an API, but I'm having trouble accessing all the arrays to get to the data. Currently, I am only able to fetch the posts arrays in a single call and not beyond that. https://i.stack.imgur.com/aFWlD.jpg My method fo ...

In Typescript, it mandates that a string value must be one of the values within the object

There is a constant declaration mentioned below: export const Actions = { VIEW: 'view', EDIT: 'edit', }; Imagine there's a function like this: // Ensuring that the action variable below is always a string with value either ...

The mat stepper must remain visible for all states, even when inactive

I am currently utilizing mat stepper and it automatically collapses all inactive states. However, I do not want this behavior. Instead, I would like to display the inactive states in expanded mode as well. <mat-vertical-stepper #stepper [linear]="isL ...