Utilizing Dynamic User Query Parameters in Mongoose for Enhanced $all Queries

Utilizing the schemas below to represent product specifications,

const MoldSpecific = new Schema(
  {
    name: {
      en: String,
      ar: String,
      kr: String,
    },
    values: [MoldValue.schema],
  },
  {
    versionKey: false,
  }
);

export default model("MoldSpecific", MoldSpecific);

const MoldValue = new Schema(
  {
    name: {
      en: String,
      ar: String,
      kr: String,
    },
    unit: { type: String, default: "" },
  },
  {
    versionKey: false,
  }
);

export default model("MoldValue", MoldValue);

Users can select various specifics such as color or manufacture year, size, etc. To handle query parameters and construct the query, the code snippet below is used. However, encountering issues while mapping or joining elements in the array:

export function getQueryParams(query) {
var queryParams = {};
  var specsParams = [];
  if (query.year) {
    specsParams.push({ $elemMatch: { "values._id": query.year } });
  }
  if (query.color) {
    specsParams.push({ $elemMatch: { "values._id": query.color } });
  }
  queryParams["specifics"] = {
    $all: [specsParams.join()],
  };
  console.log(queryParams);
  return queryParams;
}

Despite using both map and join functions with specParams array, it results in an error:

ObjectParameterError: Parameter \"obj\" to Document() must be an object, got [object Object],[object Object]"

Note: The following code snippet works successfully:

queryParams["specifics"] = {
    $all: [specsParams[0]],
  };

Any assistance or insights would be greatly appreciated.

Answer №1

There is no requirement to sign up; just provide the array like this:

queryParams["specifics"] = {
    $all: specsParams,
 };

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 babel-preset-es2016 plugin is in need of the babel-runtime peer dependency, however it seems that it

While I am aware that npm no longer automatically installs peer dependencies, why do I still receive a warning after manually installing them? ➜ npm install babel-runtime -g /usr/local/lib └─┬ <a href="/cdn-cgi/l/email-protect ...

The vuex store does not activate in routed components

After setting up my vuex store and ensuring that everything is functioning properly, I encountered an issue where I can only commit mutations in components that are directly imported into src App.vue. For instance, the resetState function in Header.vue su ...

AJAX response for form validation

I need to validate my contact form when the submit button is clicked. If all fields are valid, I want to display a Processing message using AJAX, followed by a success message with the entered name. The content of my Form is: <form onsubmit="return va ...

Evaluating the functionality of express.js routes through unit testing

Just dipping my toes into the world of express and unit testing. Take a look at this code snippet: const express = require('express'); const router = express.Router(); const bookingsController = require("../controllers/bookings"); router .r ...

React- hiding div with hover effect not functioning as expected

I'm having trouble using the :hover feature in CSS to control the display of one div when hovering over another, it's not functioning as expected. I've successfully implemented this on other elements, but can't seem to get it right in t ...

What is causing the Unhandled Promise Rejection error when using await with Promise.all?

This is the general setup of my code: (async () => { try { const asyncTasks = [] for (let i = 0; i < 3; i++) { await new Promise((resolve, reject) => setTimeout(resolve, 1000)) for (let j = 0; j < 3; j++) { async ...

What is the process for configuring MongoDB to be accessible from my local Windows network?

I am trying to share a MongoDB database from one Windows computer to all the others on the same network. I have looked for solutions on Stack Overflow, but haven't found any that address this specific issue. My attempts so far include opening port 270 ...

Even after being removed from the DOM using Ajax load, JQuery continues to execute

Currently, within my Laravel 5.2 single page application development, I am faced with the following issue. I have an add.blade.php file and an edit.blade.php file, both containing a script with the same class name and id. When I use .load to load add.blade ...

Having trouble with a JavaScript element not responding to clicks when displayed inline?

Currently, I am utilizing the "Hotel Datepicker" script found at this website: My goal is to have the datepicker always displayed inline, rather than closing after selecting dates. I attempted to add a function that triggers whenever the datepicker close ...

What is the best method to save a screenshot to your local drive without any annoying pop-ups?

I am looking to save a screenshot locally without displaying a download popup. (function() { 'use strict'; $("body").prepend(` <button id="btCapture">SCREENSHOT</button> <input type="sub ...

Dropbox menu within an extended webpage

I am looking to create a dropdown menu that behaves like the one on this website. The goal is for the dropdown to cover the entire webpage, hide the scroll bar, and "unmount" the other elements of the page, while still displaying them during the transition ...

How can I create a consistent copy button function for an HTML table that works the same across different browsers like Firefox and Chrome?

I am encountering an issue where copying the second row of an HTML table to paste it in an Excel file works perfectly in Firefox, but not in Chrome. When pasting in Chrome, the cells do not match and only the HTML inside the table cells is retained. I am u ...

Guide to refreshing the modal component with updated properties

In my application, I have created a modal component for managing recipes. This modal allows users to save recipes to a list. let modal = <Modal saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/> However, I also want to utilize the same m ...

Error encountered when using Prisma Client in conjunction with Next Auth.js

I encountered an error while working on Next Authentication with the Google adapter. The specific error message is as follows: ✓ Compiled /api/auth/[...nextauth] in 371ms (70 modules) (node:9269) [DEP0040] DeprecationWarning: The `punycode` module is dep ...

Bring in React components using a specific namespace

Here is the structure of my React component: /build .............................. /lib /inner /InnerComponent.js /index.js /OuterComponent1.js /OuterComponent2.js /index.js ................................. package.jso ...

Encountering problem with scooping in Node.js

Here is the code snippet displaying an empty object ( {} ) // declarations at the top let mainData = {}; let trainStations = {}; let routes = {}; let trainNo = {}; data["data"].forEach(async (element) => { const response2 = await fe ...

What is the best way to introduce a time delay between two JavaScript functions?

Here is some JavaScript code that I am working with: clientData.reloadTable( "CreateCSV", "/create/file" ); $("#downloadFrame").attr("src","/download/download"); The first statement in the code above creates a CSV file on the disk. The second statement d ...

Using C# and Redis for efficiently managing text files by importing and eliminating duplicates from a large dataset

It's been a while since I delved into C#, so please be patient with me as I try to solve this complex problem: I'm currently using a jruby script to sift through 900 files ranging from 5 Mb to 1500 Mb in size to identify any remaining duplicates ...

The useEffect callback is not functioning when using an empty array

I have a problem with my useEffect hook - it keeps running endlessly even though it fetches the data correctly. However, when I try using an empty array as the dependencies parameter to make it run only once, it doesn't work at all. Here is the front ...

It is not possible to include a new property to an object while inside a function

Looking to add a property to an object? Check out the code below: import React from 'react'; import { Link } from 'react-router-dom'; const Question = () => { let active; const handleClick = (iconName) => { active = {}; ...