Unable to invoke a function in JavaScript

When I try to create a user in the database by calling the function createOne inside createProfile, it seems like the function is not getting executed. Even though the route is functioning properly, I'm facing an issue with calling a function within another function.

I could really use some assistance here!

exports.createOne = Model =>
  catchAsync(async (req, res, next) => {
    console.log("I am in createone")

    const doc = await Model.create(req.body);

    res.status(201).json({
      status: 'success',
      data: {
        data: doc
      }
    });
  });
exports.createProfile = (req,res) => {
    console.log(req.query.segment);
    if(req.query.segment == "Tour"){
        let Segment = Tour;
        console.log(factory);
        factory.createOne(Tour);
    }

}

Upon checking the console log results below, it appears that the function is not being triggered at all.

Tour
{ getOne: [Function], createOne: [Function] }
POST /api/v1/midasCommon/?segment=Tour - - ms - -

Answer №1

Upon reviewing the definition of catchAsync that was provided, it seems that the function being returned is not being executed.

const catchAsync = fn => { 
  return (req, res, next) => { 
    fn(req, res, next).catch(next);
  };
}; 

When you call factory.createOne(Tour);, you are only invoking catchAsync without executing the returned function.

To correct this, you can either call factory.createOne(Tour)(); or update the createOne function as follows:

exports.createOne = Model =>
  catchAsync(async (req, res, next) => {
    console.log("I am in createone")

    const doc = await Model.create(req.body);


    res.status(201).json({
      status: 'success',
      data: {
        data: doc
      }
    });
  })(); // <-- Make sure to include the call

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

The Fetch API seems to be having trouble loading the data from localhost:300

I am facing an issue with my express-js server that returns an array of data. I want to use the Fetch API to make a request and display this list on the screen. However, every time I try to make a request, I encounter an error stating "Fetch API cannot loa ...

Tips for configuring ejs data within the data attribute and processing it using client-side JavaScript

My aim is to transfer leaderboard information from the server to the client-side JavaScript. This is the code on my server side: const leaderboard = [[dog,cat],[car,bus],[foo,bar]] const toJson = JSON.stringify(leaderboard) res.render('gam ...

Vue: Order Conflict. A new module has been incorporated into the system

Whenever I try to run my program, something unexpected happens; How can I resolve this issue? I don't want to overlook it; I searched online and found suggestions to change the component order, but after checking my code, it didn't work; Any i ...

Switch between showing the Font Awesome TitleText and its associated Class with a single click

Can the value of the title attribute for <i> be toggled? For example, if the title is set to <i title="Favorite This Post" class="fa fa-star-o" aria-hidden="true"> within <div class="postoption"> I would like to toggle both the title te ...

Performing an AJAX call every half-hour using JavaScript

I am looking to implement an ajax request every 30 minutes using JavaScript. Specifically, for the user currently logged in, I aim to retrieve any notifications that have a start date matching the current time. These notifications are set by the user with ...

Postgres error in NodeJS: Cannot resolve address - ENOTFOUND

My connection string for accessing my AWS database is pg://user:pass@localhost:port/table. It works perfectly fine when connecting to localhost, but as soon as I attempt to connect to the AWS server, everything falls apart. Even a simple connection code r ...

dealing with the same express routes

I'm currently in the process of developing an application using NodeJS/Express/Mongoose. One of the challenges I'm facing is defining routes for suspending a user without causing any duplication. At the moment, I have routes set up for creating ...

Encountering difficulties while trying to access the SQLite database file through a JavaScript Axios GET request

Having trouble opening an sqlite DB file from a js axios.get request which is resulting in an exception message being outputted to the console. The request is supposed to call my PHP controller to retrieve data from the DB and return it json-encoded. On t ...

Discovering the properties of a class/object in a module with Node.js

Recently I delved into the world of node.js and found myself puzzled about how to discover the attributes, such as fields or properties, of a class or object from a module like url or http. Browsing through the official documentation, I noticed that it on ...

Combining multiple directories into a single output using the rollup command

Alright, let's talk about my directory setup: mods/ -core/ --index.js --scripts/ ---lots of stuff imported by core/index Currently, the typical rollup process works smoothly if you want to create something like mods/core/index.min.js. However, I ha ...

What's the best way to ensure that all other routes remain operational while one route is busy handling a large database insertion task?

Currently, I am working on a project using node.js with express framework and mysql with sequelize ORM. In this method, an API is utilized to retrieve a large amount of data which is then stored in a database table. The data is in CSV format and I am util ...

What is the best way to upload images to the Cloudinary server using Multer middleware in Node.js, following validation of the form data from req.body

Hey, I would like the image to be uploaded only after passing through all validation logic and then store it on the server. Currently, I am using multer middleware. How can I modify it so that the images are uploaded to the Cloudinary server after all vali ...

ClassNames Central - showcasing a variety of class names for interpolation variables

Seeking guidance on creating a conditional statement to set the className for a div element. The conditional is functioning correctly, and I can see the className being assigned properly in the developer console. However, I am struggling to return it as ...

Tips for moving and filling data in a different component using NextJS

Currently, I am developing an application using Next.js and tailwindcss. The Issue In essence, I have a table consisting of 4 columns where each row contains data in 3 columns and the last column includes an "Update" button. The data in each row is genera ...

Tips for populating a textfield with data from a <select> dropdown using javascript

Is there a way to populate a textfield with data automatically based on information provided in the tab, utilizing JavaScript? Additionally, is it possible to prevent the filled data from being edited? The textfield should be able to dynamically fill data ...

Can you assist in resolving this logical problem?

exampleDEMO The code above the link demonstrates how to control input forms based on a button group selection. In this scenario, when a value is inputted on the 'First' Button's side, all input forms with the same name as the button group ...

Struggling to compute the mean using MongoDB

It's puzzling to me why I cannot calculate the average using Spring 5 and MongoDB. There are 40 entries in the database with the following format: Result(id=5e4adeca9eab5f052e2ac239, date=2020-02-12, value=1.048097596376957) I am interested in ...

Variables specific to Docker, dokku-redis deployment

Having issues with using redis as the session store in my express.js app. Zeroed in on a connection problem. How can I access a docker environment variable inside an express.js application? Working with dokku-redis. I have linked my app and running dokku ...

What's causing these divs to be misaligned in various directions?

I am currently working with a front-end framework based on flexbox called Material-UI, and I have noticed that the layout of certain components, particularly the quantity control elements, appears to be different even though they all share the same styling ...

Start up a server-side JavaScript instance utilizing Express

My journey into web programming has led me to learning JavaScript, Node.js, and Express.js. My ultimate goal is to execute a server-side JavaScript function (specifically a function that searches for something in a MySQL database) when a button is pressed ...