The issue lies with Mongoose's inability to convert a string into an object key

When making an ajax call, I pass the object below to Mongoose:

{category: 'name', direction: 1}

To sort the query results using Mongoose, I use the following code:

Site.find(query).sort(sortBy)

Prior to this call, I need to format the object from the ajax request correctly and insert it into the query. Here's how I do it:

let sortBy = {};    
let tmp = req.query['sortBy'];
sortBy.category = tmp["category"];
sortBy.direction = tmp["direction"];

Unfortunately, I encounter this error:

TypeError: Cannot read property 'toString' of undefined

When I log tmp to the console, I see:

tmp {"category":"name","direction":1}

However, when I log tmp["category"] and tmp["direction"], I get:

undefined undefined

Why am I unable to parse the strings into object keys?

UPDATE:

The workaround below works fine, but I'm still puzzled about why the initial code doesn't work:

var tmp = {};
var sortBy = {};

Object.keys(req.query).map(prop => {
  if (prop === 'direction') {
    tmp[prop] = parseInt(req.query[prop]);
  } else if (prop === 'category') {
    tmp[prop] = req.query[prop]
  }
});

sortBy = {[tmp.category]: tmp.direction};

Why do I require this tmp object?

Answer №1

I faced the same problem before too. The key is to make sure to properly define field definitions in the schema, or else they might end up being undefined.

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

Using JQuery with the latest version of Google Sites is a game-ch

My coding knowledge is very limited, especially beyond VBA. I've hit a roadblock and it seems like I'm overlooking something obvious. What I'm attempting to accomplish: I need this code to be integrated into a New Google Sites page (which h ...

The unrevealed node that is requesting the module is leading to an undefined outcome

I'm facing an issue where I need to import var server = require('../../index.js'); in my foo-dao.js file. This is necessary for accessing a hapi server plugin without passing it through the hapi request object from controller to dao. The pr ...

Is there a way to convert a button into clickable text that performs the same function as the original button?

Seeking a solution to transform a button into clickable text with the same functionality. Explored resources like Google, StackOverFlow, and Youtube for answers. This is the current code snippet representing the button: <button onclick="mainApp.l ...

The dynamic route parameter does not currently have compatibility with languages that utilize Unicode characters apart from the English

NextJS 13 (beta) Official Documentation provides information on dynamic route parameters in this link. Clarification: app/shop/[slug]/page.js To retrieve the slug, use params.slug. Example: app/shop/this-is-shop/page.js In this case, params.slug will o ...

Exploring ways to access data stored in interconnected models, such as MongoDB and NodeJS

As a newcomer to querying, I attempted a unique exercise to practice but unfortunately did not achieve the desired outcome. I have three models: const userSchema = new Schema({ info1: String, info2: String }, const serviceSchema = new Schema( { name ...

Toggling forms with HTML <select> elements: A step-by-step guide

In the process of creating a web application, I am faced with the task of registering users based on their specific category. To accomplish this, I have incorporated a combo-box where users can indicate their user type. My objective is to display an appro ...

Loaded Ruby gem, however receiving error: "constant uninitialized"

I'm puzzled by the following result: $ rails c Loading development environment (Rails 3.2.14) 1.9.3p392 :001> require 'rubygems' => false 1.9.3p392 :002 > require 'mongo' => false 1.9.3p392 :003 > include Mongo ...

Successively linking promises together within a for-each iteration

How can I ensure that a foreach loop is synchronous in AngularJS var articles = arg; articles.forEach(function(data){ var promises = [fetchImg(data), fetchUser(data)]; $q.all(promises).then(function (res) { finalData.push(res[1]); ...

Fetching data from different interfaces with the same name in Angular

In my project, I have two interfaces - one is cropFilter for checkbox filtering and the other is Crop which holds the data. Let me provide you with the code for better clarity. 1. crop.model.ts export class Crop { // Interface 1 name: string; dis ...

Creating a file by piping the output of an asynchronous HTTP request while utilizing async await method

I have been diligently following the instructions and conducting thorough research for a whole day to figure out how to use a pipe to compile an Excel spreadsheet that is fetched through an API call. I managed to get part of the way in saving it, but unfor ...

Utilize AJAX and JavaScript to retrieve file information and facilitate file downloads

I have developed a script that intercepts Captcha form submissions. Typically, when the form is submitted, a file will be downloaded (such as exe or zip) in the usual way where it appears at the bottom of the Chrome browser and gets stored in the "download ...

Tips for updating a value in a React TextField using handleChange function

After clicking a button, I need to dynamically set a value in this textfield: <TextField fullWidth inputProps={{ maxLength: 75 }} key="nomeSocial" id="outlined-basic" label="Nome Social" name="nomeSocial&qu ...

Invoke a handler from one function within another function

I am unsure of the best approach for achieving this, or if it is even feasible, but I have two components: a main navigation bar (NavBar) that spans across the top of the page, and a sidebar drawer. NavBar: export default function NavBar() { const c ...

Distinctive titles for JavaScript constructors/prototypes compared to classes

When working with JavaScript ES6, classes allow us to write code like this: class RectangularShape { constructor(height, width) { this.height = height; this.width = width; } getArea() { return this.height * this.width } static some ...

Verify if a certain value is present within a nested array

I need assistance with checking if a specific value is present within a nested array. Here is an example of the data I am dealing with: [ { name: 'alice', occupation: ['Artist', 'Musician'], }, { ...

Is it possible to toggle between hide and show functions using Jquery?

I have a question about two jquery functions that I've been struggling with. $(document).ready(init); function init() { $(".alphaleft").hover(function (g) { $(".boxy,.yee").show(); }, function (g) { $(".boxy,.yee").hide(); }); } ...

Tips on viewing class object values within the `useEffect` hook

App.js import React, { useRef, useEffect } from "react"; import Token from "./Token"; export default function App() { const tokenRef = useRef(new Token()); useEffect(() => { console.log("current index of token: ", ...

Angular 2's Multi-select dropdown feature allows users to select multiple options

Recently, I encountered an issue with customizing CSS for angular2-multiselect-dropdown. I found the solution in this link: https://www.npmjs.com/package/angular2-multiselect-dropdown. I have included my code below. Any assistance in resolving this matter ...

Creating a new image by converting canvas to an image and displaying it in a separate window with Ruby on Rails and

I'm having some trouble with this issue and would really appreciate your help. My goal is to convert a canvas into an image using toDataURL when a link, button, or image is clicked. Once the image is generated, I want it to open in a new window. Can ...

The component name "pages/product/_slug.vue" is invalid as it does not adhere to the valid custom element name specified in HTML5

Currently, I am working with Nuxt.js and dealing with some dynamic routes. The folder structure I have set up looks like this: - pages - product - _slug.vue For linking to the route, I am using the following code: <nuxt-link :to="{ name: 'pro ...