The error thrown by Mongoose, stating "TypeError: Cannot read property 'catch' of undefined," is not caught after the data is saved

After updating to Mongoose version 5.0.15, I encountered an error that says

TypeError: Cannot read property 'catch' of undefined
when trying to save my object with errors found, even though everything was working fine on Mongoose version 4.13.11.

It seems like the issue lies in the fact that the Save() function does not return a Promise. Despite using bluebird, which was functioning properly before, the current implementation is failing with the updated version.

I'm unsure of what I might be doing wrong since the .catch() should be working as intended.

app.ts

mongoose.Promise = bluebird;
mongoose.connect(mongoUrl).then(
  () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
).catch(err => {
  console.log("MongoDB connection error. Please make sure MongoDB is running. " + err);
  // process.exit();
});

Home.ts

let user: userInterface = {
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8a8383ac8e8d9ec28f8381">[email protected]</a>",
        firstName: "Brian",
        lastName: "Love",
        password: "as",
        role: 1,
        accountType: 1
    };

    var newUser = new User(user);      // create a new instance of the User model

    // save the newUser and check for errors
    var a=  newUser.save(function(err) {
        if (err){
            return err;
        }
        res.json({ message: 'User created!' });
    }).catch(function (error) {
        console.log(error);
    });

Answer №1

Two ways to trigger save function in mongoose

  • Using Promises
  • Using Callbacks

Using Promises

newUser.save().
    then((data) =>{
        console.log("saved data ",data);
        res.json({ message: 'User created!' });
    }).catch(function (error) {
        console.log(error);
        res.json({ message: 'User not created!' });
    });

Using Callbacks

newUser.save(function(err,data) {
    if (err){
        console.log(error);
        res.json({ message: 'User not created!' });
    }
    else{
        console.log("saved data ",data);
        res.json({ message: 'User created!' });
    }
})

To enable promises in mongoose, you can set this option

mongoose.Promise = global.Promise;

Check the Documentation for more information http://mongoosejs.com/docs/models.html

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

"Take control of FileUpload in PrimeNG by manually invoking it

Is there a way to customize the file upload process using a separate button instead of the component's default Upload button? If so, how can I achieve this in my code? Here is an example of what I've attempted: <button pButton type="button" ...

Troubleshooting Image Upload Problem with Angular, Node.js, Express, and Multer

While trying to implement the functionality of uploading an image, I have been referencing various guides like how to upload image file and display using express nodejs and NodeJS Multer is not working. However, I am facing issues with getting the image to ...

Next.js encountering issue due to mismatched Node.js version

I am new to working with node.js and next.js, and I recently began a project using Next.js. When I tried running npm run dev An error popped up saying: You are currently on Node.js 18.12.1. However, for Next.js, you need to be on Node.js version >= ...

Node.js server crashes unexpectedly

Hey there, I'm reaching out for some assistance with my project. I am trying to showcase Rainbow Six statistics using this API: https://www.npmjs.com/package/rainbowsix-api-node I have set up a Node server and Express, along with a React frontend. Ho ...

Begin your meteor project with a remote MongoDB server on a Windows operating system

Currently tackling a project that requires me to integrate my meteor project with a remote MongoDB server on Windows. I successfully set the environment variable (MONGO_URL="DB LINK") from OSX using terminal commands, but I'm encountering difficulties ...

Logging client IP addresses in your Express application using Winston

Utilizing express-winston as a middleware within Express for logging all request details and response codes. Below is the code snippet that I am using: const myFormat = printf(info => { console.log(info) return `${info.timestamp} ${info.level}: ${i ...

sharing data between two node.js servers using http

I am currently working on integrating two node.js/express servers that communicate with each other using HTTP. One of the servers, known as server A, is responsible for handling file upload requests from the browser. My goal is to seamlessly transfer any u ...

The lambda function is encountering a MySQL error stating that it cannot find the module 'mysql' and is not functioning properly, even after being included in the zipped file

I set up a lambda function using the following steps. First, I created a new folder and initialized a new project by running npm init in the command line Next, I added my code to index.js and installed the mysql package locally by running npm insta ...

Problem with extending a legacy JavaScript library using TypeScript

Can someone assist me with importing files? I am currently utilizing @types/leaflet which defines a specific type. export namespace Icon { interface DefaultIconOptions extends BaseIconOptions { imagePath?: string; } class Default exte ...

Contrasting the inclusion of the "route" keyword when defining routes in Express

Can you explain the distinction between router.route('/create') .post(validate(hotelValidation.createHotel), function (req, res) { and just router.post('/create', validate(hotelValidation.createHotel), function (req, res) { Are ...

The `Required<Partial<Inner>>` does not inherit from `Inner`

I stumbled upon a code snippet that looks like this: type Inner = { a: string } type Foo<I extends Inner> = { f: I } interface Bar<I extends Inner> { b: I } type O<I extends Partial<Inner>> = Foo<Required<I>> & B ...

Exploring the integration of Styled-components in NextJs13 for server-side rendering

ERROR MESSAGE: The server encountered an error. The specific error message is: TypeError: createContext only works in Client Components. To resolve this issue, add the "use client" directive at the top of the file. More information can be found here i ...

Issue with Redis cache time-to-live not adhering to set expiration

I have encountered an issue while using IoRedis and DragonflyDB to implement rate limiting in my web application. Despite setting a TTL of 5 seconds for the keys in the Redis DB, sometimes they do not expire as expected. I am struggling to understand why t ...

How can a TypeScript object be declared with a single value assignment to itself?

Whenever I try to declare an object and assign a key to itself, I encounter errors. I have attempted different methods, but the error persists. const a = { d:123, a:a//<-TS2448: Block-scoped variable 'a' used before its declaration. } co ...

Having trouble storing data in a MYSQL database with NodeJS and ReactJS

When trying to submit the form, a "Query Error" popup appears and data is not being saved in the database. API router.post("/add_customer", (req, res) => { const sql = `INSERT INTO customer (name, mobile, email, address, state, city, policytype, insu ...

Protractor throws an error when trying to display toast notifications due to a "RangeError: Maximum call stack size exceeded"

I've attempted to test the behavior of toast notifications using the code snippet below (refer to the latest code block): describe('vCita Frontage - Conversation test cases', function() { var EC = protractor.ExpectedConditions; var ...

Adding JSON data to an array in Node.JS

I am facing an issue where my JSON data is successfully being appended to an array inside a JSON file. However, the problem is that it is not appending inside of the brackets in the JSON file. Below is the code snippet for my NODE if (req.method == &apo ...

The Node-Express application is unresponsive when trying to connect with external servers

In the first Virtual Machine, I have a basic node script set up. // server.js var express = require('express'); var annotations = require('./routes/annotations'); var cors = require('cors'); var app = express(); app.use(cors( ...

Error: An unexpected issue occurred when attempting to iterate over the snapshot

I recently started exploring nodejs and Google Cloud FireStore. Below is the code that I am currently working on. createNewPage = function (title, header, content, db ) { let pageRef = db.collection("pages").doc(title.trim()); let setPage = pag ...

The array containing numbers or undefined values cannot be assigned to an array containing only numbers

Currently facing an issue with TypeScript and types. I have an array of IDs obtained from checkboxes, which may also be empty. An example of values returned from the submit() function: const responseFromSubmit = { 1: { id: "1", value: "true" }, 2: ...