Searching by object id from the front-end: A step-by-step guide

Within my collection of meals, there is a specific document I am working with:

# Meals collection
{
   name: "burger",
   tag: ObjectId(63d6bb22972f5f2fa97f1506),
}

Now, as I navigate through my React application, I find myself needing to send a query to my backend API.

To achieve this, I crafted a request that looks something like this:

const tagId = "63d6bb22972f5f2fa97f1506"
const queryString = `http://localhost:3001/v1/meals?tag=${tagId}`
sendQuery(queryString)

This query travels to the server following a RESTful pattern:

http://localhost:3001/v1/meals?tag=63d6bb22972f5f2fa97f1506

When it reaches the back-end, I handle the search parameters in this manner:

// # nodejs server-side
// # using expressjs
// # and using mongoose
api.get('/meals', async (req, res, next)=> {
 const res = await MealModel.find(req.query) // req.query = { tag: "63d6bb22972f5f2fa97f1506" }
  res.status(200).json({
    status: 'success'
    data: res
  })
})

Despite my efforts, the query returns an empty array [], due to the mismatch between the tag type being an object ID instead of a string.

Your req.query.tag is currently receiving a string rather than an object ID.

The question arises: how can one transmit an object ID from the front-end to the back-end via JSON?

It may seem perplexing, but fear not! Let's explore potential solutions together.

Answer №1

const mongoose = require("mongoose")

api.get('/meals', async (req, res, next)=> {
 const result = await MealModel.find({category:mongoose.Types.ObjectId(req.query.category)})
  res.status(200).json({
    status: 'successful'
    data: result
  })
})

Additionally, if there happens to be only one entry in your Meals collection, consider using findOne instead for faster execution of your query. Feel free to give it a try and let me know how it goes. I hope this suggestion proves helpful.

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

JavaScript Sort function malfunctioning and not correctly sorting

I am having trouble sorting div elements by price values. The code seems to be working fine, but the sorting of numbers doesn't appear to be completely accurate. For example, in my jsfiddle, when the button is clicked, the number 21.35 is displayed a ...

`"Type is invalid" error occurring with component after importing it into a different project``

I am currently working on developing a custom Storybook 7 Typescript component library with React. I have successfully imported this library into another project using a private NPM package. However, one of the components in the library, specifically the ...

Using ThreeJS to Apply Dual Materials to a Mesh Entity

With ThreeJS, it's possible to incorporate more than one material into an Object3D/Mesh as stated in the documentation. You can either utilize a single Material or an array of Material: Class declaration and constructor for Mesh TypeScript file (exce ...

The progress bar in Next JS 13 seems to be malfunctioning and is not displaying any

After transitioning to the new Next JS 13 app directory, I encountered an issue where the progress bar at the top does not function when the page loads. In the previous version, Next JS 12, there was a package named nprogress and nextNprogress that simpli ...

Trouble with sending data to child components via props

I've been trying to pass a prop to a child component in React, but when I check the props using console log, it doesn't show up at all. Even the key things is missing from the props. Any assistance with this would be greatly appreciated. export ...

Loading images in real-time from the server for an HTML gallery

Recently, I implemented a dynamic wowslider gallery that loads images from a specific folder. The issue I encountered is that all the images load simultaneously, causing a delay in loading time. My goal is to load the images one by one in order using JavaS ...

Extract a section of the table

I'm looking to copy an HTML table to the clipboard, but I only want to include the rows and not the header row. Here is the structure of the table: <table style="width:100%" #table> <tr> <th class="border"></th> ...

What could be causing the directory to display a 404 error when trying to render ejs

I'm working on a page that should only receive a get request from my index.js file and display "hello user". In my express app, I have created a 'users.ejs' file that renders a string from a 'users.js' file. There is a form in my i ...

Exploring Angularjs: Navigating to a particular element within ng-repeat

I created a custom directive that generates a list of buttons using ng-repeat: HTML <div ng-controller="toggleButtonController" ng-init="init()" id="parent"> <div ng-repeat="btn in setting" style="display:inline"> <button class ...

Getting the value of a variable inside an onclick function

I am facing an issue with displaying the values of 2 variables inside an onclick event. I have tried the code below but it is not working. Can someone please help me solve this problem within the next 3 hours? var myCode = "12345"; var myCount = "5" $(&a ...

Is there a way to determine if the value of an array has not been defined?

When attempting to access the value of an array that does not exist, an error is thrown stating "variable is not defined." Consider the following example: var arr = new Array(); arr['house']['rooms'] = 2; Using the following check: ...

User Verification Secure System

As I am just starting out with node/express, I am facing an issue with my todo application. The application is built using node js, express, and mongo db with a login/register form. Users need to register and login (/register) and (/login) before accessing ...

How to attach a custom event to a nested component in Vue.js when using a for loop

I have implemented a system using three single-file-components. ParentVariation.vue VariationInfo.vue Childvariation.vue In this setup, the variation-info child component emits a MarkedFilled event which is then caught by the ParentVariation component. ...

Avoid reloading the menu in order to update the page using Jquery-Ajax

I am currently working on a function to reload the page without affecting our menu, which is an accordion. The goal is to refresh the page while keeping the menu in the same state. Below are the jQuery functions I am using to handle the page reload and en ...

Relationship between multiple Mongoose instances linking to a single entity

Having an issue regarding mongoose and relationships. My "Athletes" collection has the following schema: var athletesSchema = mongoose.Schema({ name : String, regionName : String, age : Number, overallScore : Number, scores : { ordinnal : String, ...

Retrieving value from the parent scope using the conventional approach

Today I was puzzled by some unexpected behavior of AngularJS. While using console.log to log $scope, I noticed that there was no key attached to the scope named val1. However, when I used console.log($scope.val1), it returned a value as an object. After ...

The process of executing a PHP file from JavaScript using XMLHttpRequest is experiencing issues on a XAMPP local server

I'm attempting to execute a PHP file using JavaScript. I have my XAMPP server set up and all files saved in the htdocs folder. The PHP file is also stored in the htdocs folder and works correctly when accessed via http://localhost/php_test.php in Chro ...

What is the best way to display the absent months in a mongo aggregate query with a value of 0?

Is it possible to ensure that the missing months in the aggregate result have a BruteAmount value of zero? Purpose This code aims to generate two arrays containing the month names and their respective BruteAmounts. The data should be ordered by the curre ...

What is the process for configuring simultaneous services on CircleCI for testing purposes?

My current project involves running tests with Jasmine and WebdriverIO, which I want to automate using CircleCI. As someone new to testing, I'm a bit unsure of the process. Here's what I've gathered so far: To run the tests, I use npm tes ...

Guide to incorporating Moengage into Node.js APIs for delivering email notifications based on user interactions

How can Moengage be integrated into Node Js APIs for sending notifications to users based on user events? I have reviewed the Moengage API documentation but did not find relevant information on integrating Moengage with Node Js APIs. Is there a step-by-s ...