Providing input to a nested mongoose query

I can't figure out why I keep experiencing 504 Gateway timeouts.

app.get("/api/exercise/log", function(req,res) {
  let userId = req.query.userId;
  let from = req.query.from;
  let to = req.query.to;
  let limit = req.query.limit;
  console.log("limit1 " + limit);
  User.findById(userId).exec(function (err,data) {
    console.log("limit2 " + limit);
    if (err) return err;
    Exercise.find({userId: userId}).limit(limit).exec(function (err2,data2) {
      console.log("limit3 " + limit);
      if (err2) return err2;
      let logArr = [];
      logArr.push(data2);
      let total = logArr[0].length;
      let answer = Object.assign({}, data._doc, {log: logArr}, {total: total});  
      res.json(answer);
    })    
  })  
})

My url ends with log?userId=555&limit=2. Despite all console logs (limit1, limit2, limit3) correctly printing '2', I am still encountering only timeouts. However, when manually setting the limit value to 2 as shown below:

Exercise.find({userId: userId}).limit(2).exec(function (err2,data2) {

everything seems to work fine and I receive the accurate number of results. What could be causing this inconsistency?

Answer №1

Use parseInt to convert a string to a number and validate if it can be converted successfully.

app.get("/api/exercise/log", function(req,res) {
  let userId = req.query.userId;
  let from = req.query.from;
  let to = req.query.to;
  let limit = 10;
  if(!isNaN(req.query.limit)){
      limit = parseInt(req.query.limit);   // set limit to query parameter value if it's a valid number
  }
  console.log("limit1 " + limit);
  User.findById(userId).exec(function (err,data) {
    console.log("limit2 " + limit);
    if (err) return err;
    Exercise.find({userId: userId}).limit(limit).exec(function (err2,data2) {
      console.log("limit3 " + limit);
      if (err2) return err2;
      let logArr = [];
      logArr.push(data2);
      let total = logArr[0].length;
      let answer = Object.assign({}, data._doc, {log: logArr}, {total: total});  
      res.json(answer);
    })    
  })  
})

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

What is the best way to display all filtered items in PyMongo?

I'm relatively new to the world of programming and currently facing a challenge with filtering my MongoDB data in order to display all the retrieved elements. When retrieving a single element, I don't encounter any issues. c = db.get_collection ...

I'm struggling to figure out how to apply the push operator in an aggregation function using an array. Whenever I attempt to do so, I encounter an error stating that

Looking for patients with both a history of cough and headache in their medical records. In each medical record, symptoms are recorded in fields "SYMPTOM_1, SYMPTOM_2" After running the query below, I encountered the following error: exception: aggregat ...

The method to permit a single special character to appear multiple times in a regular expression

I am currently working on developing a REGEX pattern that specifically allows alphanumeric characters along with one special character that can be repeated multiple times. The permitted special characters include ()-_,.$. For instance: abc_def is conside ...

Tips for resolving the issue: React is unable to recognize the X prop on a DOM element

I have been experimenting with a library known as react-firebase-js for managing firebase authentication. However, my grasp of react and the concept of provider-consumer is somewhat limited. Initially, I created a large JSX construct at the top level, whi ...

The intended functionality of clicking on an image is exclusively reserved for its immediate parent element

I have a feature on my website that displays an image gallery. When a user clicks on an image, it opens up the image in full screen similar to Facebook's theatre mode. I have written code so that when the user clicks anywhere in the container of the i ...

Internet Explorer 8 halts the progress of the loading animated GIF

When I call an animated loading gif image on an <asp:Button> click event in the client side code, the animation stops in IE8 while the server-side code is executing. This issue does not occur in Mozilla or other browsers. The animation works fine wh ...

Developing a fresh instance that collaborates with other components like Sequelize, NodeJs, Express, and Postgres

Hello all, module.exports = (sequelize, DataTypes) => { const Category = sequelize.define( 'Category', { name: DataTypes.STRING, viewOrder: { type: DataTypes.INTEGER, ...

Unable to retrieve the authorization code following the redirection of the URL

Currently, I am tackling the integration of Salesforce with Slack. Unfortunately, my knowledge of javascript and related technologies is limited. Can someone please review the code and identify what might be missing? // Grab express and request modules ...

Why does Typescript not enforce a specific return type for my function?

In my custom Factory function, I need to return a specific type: type Factory<T> = () => T; interface Widget { creationTime: number; } const createWidget: Factory<Widget> = () => { return { creationTime: Date.now(), foo: &a ...

Set up Vue.prototype prior to the component loading

In my Vuejs code, I am utilizing the plugins feature to define a global shared variable. Vue.use(shared) The shared variable is defined as follows:- export const shared = { config: getAppConfig() } shared.install = function() { Object.definePropert ...

What is the best way to add HTML content to a specific div element within an AJAX call's success function?

In the provided ajax script, my goal is to insert HTML content into a specific div element inside a table. The main div element in question is named "ajaxcom", but I need to insert the HTML content into a div element with the class = "divrep". How can I ac ...

Dynamic Creation of a jQuery Selector

Dear, I'm facing an issue while trying to load data dynamically into a table using JSON format. The data is coming from a PHP file. However, despite my attempts, the table remains empty and no data is being displayed. function fetchTableData() { ...

The ng-repeats functionality is triggered multiple times whenever I attempt to make this call

I have a situation where I am using ng-repeat in my Laravel view to call a function from the controller. This function retrieves data from the database, performs some calculations, and then returns an array. However, I am facing an issue where the data is ...

Expanding the size of a textarea using JavaScript

JavaScript: function adjustRows() { var value = document.getElementById("test1").value.length; if (value <= 18) { value.rows = 1; } else if (value > 18 && value < 36) { value.rows = 2; } else if (value > 36 && v ...

What is the best way to execute an axios request within my custom API endpoint?

I am exploring making an API call to a third party within my own API route for the first time. The code I initially tried resulted in the error "Cannot use import statement outside a module." This code is executed by a thunk on the front end. If using axi ...

How to display two elements side by side within a div using React

I have an array that looks like this: const arr = [1,2,3,4,5,6,7,8,9,10] I am looking to display the elements in pairs per line within two-dimensional divs. Here is what I have in mind: This represents the main React element: render() { return <di ...

"webpack" compared to "webpack --watch" produces varying results in terms of output

My project is built on top of this setup: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html Running webpack compiles a bundle that functions correctly in the browser. However, running webpack --watch to recompile on file changes resul ...

Tips for adjusting the search bar's position on a mobile device when it is activated by the user

I need help with an open source project where I am developing a search engine using Angular. When using smaller screen sizes, the search bar is positioned in the middle but gets hidden behind the keyboard terminal when clicked on. Can anyone advise on ho ...

bringing in a nested object from an API

Check out this link: http://jsonplaceholder.typicode.com/users. In the address object, there is a geo object that I attempted to import using this method, but it doesn't display anything on the webpage. {identity.address && identity.geo & ...

Event triggered when a Socket.IO connection is disconnected

Everything seems to be working well with my code when a new user joins, but I'm encountering issues when a user leaves as it doesn't display anything. Can someone point out the error in my code? Below is my server-side code: const express = requ ...