Pass a customized field as an argument to the .find() method in mongoose

When making an HTTP call to my api to fetch documents from a mongodb, I include two parameters in the URL: campo and keyphrase. My goal is to retrieve all documents where the parameter campo is set to my specified keyphrase. For example, if I have some documents like this stored in MongoDB:

classe: "4AT"
cognome: "XYZ"
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef979695c1959697af88828e8683c18c8082">[email protected]</a>"
idreg: "IUDQFEXFFR4DW133"
nome: "Francesco"
turni: ["g2t1", "g1t2", "g3t2"]
__v: 0
_id: "5c508d0b4810fc0ece8df2a9"

If I make a GET request to "localhost:3000/nome/Francesco", I want to retrieve all documents with the value "Francesco" in the "nome" field. However, the issue lies in the fact that the .find() method only accepts parameters in the format:

.find({nome: keyphrase})

and not as dynamic headers as I would prefer. Is there a way to achieve this?

PS: Below is my Express code for handling the GET request:

app.get("/api/ragazzi/:campo/:keyphrase",(req, res, next) => {
  let campo = req.params.campo.toLowerCase();
  let keyphrase = req.params.keyphrase;
  Ragazzo.find({campo : keyphrase})
    .then(documents =>{
      res.status(200).json({
        codice: "ok",
        risultato: documents
      });
    })
    .catch((err)=>{console.log(err);});
});

Answer №1

Attempt

.search for({ [field] : keyword })

Answer №2

To execute a query based on the values of campo and keyphrase, you can create an object in advance and use it as the query

app.get("/api/ragazzi/:campo/:keyphrase",(req, res, next) => {
  let campo = req.params.campo.toLowerCase();
  let keyphrase = req.params.keyphrase;
  let query = {};
  query[campo] = keyphrase
  Ragazzo.find(query)
    .then(documents =>{
      res.status(200).json({
        code: "ok",
        result: documents
      });
    })
    .catch((err)=>{console.log(err);});
});

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

Develop a custom function in Typescript that resolves and returns the values from multiple other functions

Is there a simple solution to my dilemma? I'm attempting to develop a function that gathers the outcomes of multiple functions into an array. TypeScript seems to be raising objections. How can I correctly modify this function? const func = (x:number, ...

The VueJS component failed to import successfully

Trying a simple demo to explore VueJS components, but encountering an error when loading the page: Unexpected Token Import in this line import GISView from './components/GISView.vue'; If I remove this line, GISView is not defined. Using Laravel ...

Using PHP to perform live calculations with arrays in real time

Currently, I am working on developing a new system for a client that allows them to create bookings and invoices to send to their clients. One specific requirement my client has is the need for a table column to be added below the container columns in whi ...

Changing the position of an image can vary across different devices when using HTML5 Canvas

I am facing an issue with positioning a bomb image on a background city image in my project. The canvas width and height are set based on specific variables, which is causing the bomb image position to change on larger mobile screens or when zooming in. I ...

Unable to retrieve Java variable in JavaScript

Seeking guidance on how to retrieve Json data stored in a Java variable using JavaScript. Instead of accessing the data, the html source is displayed. Java: Gson gson = new Gson(); String json = gson.toJson(obj); request.setAttribute("gsonData", gson) ...

The react transition group fails to add the necessary CSS classes to the specified div

Regardless of whether I utilize React transition group, Tailwind, pure CSS, or any other framework, no transitions seem to occur when I structure my simple component in the following manner. I have experimented with various frameworks, but the outcome rema ...

What is preventing me from successfully retrieving data at times when using curl_setopt and jQuery Ajax?

In my quest to fetch data from another server, I am using the curl_setopt PHP function along with Ajax. The function I have created seems to be working fine, but sometimes when I refresh the page and the internet connection is slow, I don't receive an ...

What is the most effective way to locate numerous items based on their _ids in MongoDB?

Imagine having a MongoDB database that consists of two collections - 'fruits' and 'baskets'. The 'fruits' collection is filled with various pieces of information for each fruit, such as calorie content and country of origin. O ...

casperjs timeout issue with an endless loop

Currently, I am utilizing casperjs to retrieve the content of a website that updates its values using websockets. Rather than attaching an event listener to each value, my goal is to scrape the entire website every 10 seconds. Here is the code snippet I a ...

Display the input text line by line

How can I achieve the desired output for this input parameter? displayText("you and me"); expected output: ["you and me", "you and", "and me", "you", "and", "me"] I have attempted ...

relocate the figcaption below the image on mobile devices

Currently, I am in the process of updating an old website to make it responsive, and I have encountered several challenges along the way. My goal is to have the fig captions displayed on the right side in the desktop version, but underneath the figure in ...

What are the best strategies for eliminating element cloning and duplication in Vue?

As a novice programmer, I've developed a web app similar to Trello. It allows users to create boards and within those boards, lists can be created. Each list is displayed uniquely with different IDs. However, the list items are displayed with the same ...

Avoid duplicate items from being added to an array in AngularJS

I have created an Angular Single Page Application that includes a cart feature where users can add items. My goal is to prevent users from adding the same item to the cart more than once. function CartForm($scope) { $scope.products = [{ "descript ...

Creating a standalone executable for Node.js without including the entire Node.js framework

Trying to pack a simple hello world script into an executable has led to some challenges. Both pkg and nexe seem to include the entirety of Node.js in the output file, resulting in quite larger files than necessary (around 30 MB). Although EncloseJS was fo ...

Revise Script to Duplicate Alt Attribute onto Miniatures

I'm customizing a gallery plugin for a website that I am currently developing, aiming to add support for titles. The script I am using can be found here: DEMO: http://jquery.malsup.com/cycle/pager2.html CODE: All the functionalities are in place e ...

How can I access the value of a textbox within a dynamically generated div?

In my project, I am dynamically creating a div with HTML elements and now I need to retrieve the value from a textbox. Below is the structure of the dynamic content that I have created: <div id="TextBoxContainer"> <div id="newtextbox1"> // t ...

Bootstrap does not show submenus on its navigation menus

I am currently designing a menu with Bootstrap, but for some reason, the submenu items are not showing up. https://i.stack.imgur.com/qZqyf.png After carefully reviewing the HTML code multiple times, I am unable to identify any issues. I am now questionin ...

How to Pause or Temporarily Halt in Jquery?

Looking to lift the object up, wait 1000ms, and then hide it. I found this snippet of code: $("#test").animate({"top":"-=80px"},1500) .animate({"top":"-=0px"},1000) .animate({"opacity":"0"},500); However, using ".animate({"to ...

Create a selection menu in an HTML dropdown list using unique values from a JSON object that is separated by commas

I'm working with a JSON object that contains multiple key value pairs, one of which is the Languages key. This Languages key holds comma-separated values such as "English, Hindi, French," and so on. My goal is to extract distinct values from the Lang ...

Ordering dates by week in AngularJS 1

Currently, I have a list of objects: [{ name: one, date: 2017-09-18 }, { name: two, date: 2017-09-11 }, { name: three, date: 2017-09-13 }] I am looking to organize this list by week. Perhaps like the following structure: { 1week(or , m ...