Utilizing a GET method with MongoDB

My front end has a link using axios with a placeID parameter: http://localhost:3001/api/getData?placeID=Uh8LPCRstLnJ-ZY3B41N9w

I am trying to retrieve results based on the placeID in my database. I have made sure that there is data with the specific placeID, but I keep getting a 404 not found error. What could be wrong with my get request?

This is what the back end code looks like:

const mongoose = require("mongoose");
const express = require("express");
var cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");
const Data = require("./data");

const API_PORT = 3001;
const app = express();
app.use(cors());
const router = express.Router();

// MongoDB database connection
const dbRoute =
  "mongodb+srv://name:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f888998b8bb89b948d8b8c9d8ac8d588c0998accd69597969f979c9ad6969d8c">[email protected]</a>/reviews?retryWrites=true";

// Connect backend code with the database
mongoose.connect(dbRoute, { useNewUrlParser: true });

let db = mongoose.connection;

db.once("open", () => console.log("connected to the database"));

// Check if connection with the database is successful
db.on("error", console.error.bind(console, "MongoDB connection error:"));

// Parse request body to JSON format
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger("dev"));

// Get method to fetch data from the database

router.get("/getData/:placeID", (req, res) => {
  const { placeID } = req.params.placeID;
  Data.find({ placeID: placeID }, function(err, data) {
    if (err) return res.json({ success: false, error: err });
    return res.json({ success: true, data: data });
  });
});

// Launch backend on a port
app.listen(API_PORT, () => console.log(`LISTENING ON PORT ${API_PORT}`));

This is the schema defined in the data.js file:

// /backend/data.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Define data structure for the database
const DataSchema = new Schema(
  {
    placeID: String,
    seatRating: Number,
    comfortRating: Number,
    internetRating: Number,
    noiseRating: Number,
    outletRating: Number
  },
  { timestamps: true }
);

module.exports = mongoose.model("Data", DataSchema);


Answer №1

Using the path "/getData/:placeID"
indicates that placeID is specifically used as a part of the URL, not as a variable. Also, remember that 404 refers to an HTTP status code, not a MongoDb error. Make sure you are accessing the correct path like this:
http://localhost:3001/api/getData/Uh8LPCRstLnJ-ZY3B41N9w

Notice how we pass the ID similar to passing parameters and arguments? In Express, req.params.placeID will hold the value Uh8LPCRstLnJ-ZY3B41N9w

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

Introducing a Node JS web application unaccompanied by hosting services

As I prepare for a coding competition and want to display my computer's IP address, I am wondering if it is safe to type in my home computer's IP once I start serving the webapp before leaving my house. Apologies if this question seems silly. ...

The export "hasInjectionContext" is not provided by the source file "node_modules/vue-demi/lib/index.mjs", but it is being requested in the file "node_modules/pinia/dist/pinia.mjs"

Every time I launch my program, the console displays an error message stating that "hasInjectionContext" is not exported by "node_modules/vue-demi/lib/index.mjs", imported by "node_modules/pinia/dist/pinia.mjs" at line 6:9. I ...

Is it possible to have an icon change color in a TableRow column when hovering over any part of that particular row?

I am currently using material-ui version 4.9.5. To illustrate my issue, I have created a simplified example here. I have a Table that is populated with basic JSON data. Each row in the table consists of an icon element along with its corresponding color a ...

Trouble arises when attempting to bind a JavaScript event with an innerHTML DOM element

I am currently dealing with a complex issue on how to bind a JavaScript event to an innerHTML DOM element. The scenario involves having a div with an input checkbox inside it, along with some pre-existing JavaScript event bound to that checkbox. Additional ...

An issue has occurred [ERR_HTTP_HEADERS_SENT]: it is not possible to adjust headers once they have been sent to the client. It is not possible to redirect to a page other than

I'm currently working on a program where I want the server to redirect users to a different page if incorrect details are entered. The issue I'm facing is that every time I attempt to use res.redirect() with another web page as a parameter, I rec ...

What error am I making in the Date calculator for the select box using Javascript/jQuery?

$(.dateselboxes) .change( function(){ var y; y=$("#year").val(); var m; m=$("#month").val(); var d; // check for leap year var isLeapYear; if(y%4==0) { if(y%100==0) { if(y%400==0) {isLeapYear=true;} else {isLeapYear=false;} } ...

What is the common approach for directing a setState Redux action?

I am looking to streamline my state update actions in multiple react-redux reducers by creating a general setState action. This will allow me to have consistent syntax for dispatching both local and redux scope updates. For local updates, I would use this. ...

Can Express.Multer.File be inserted into a FormData object easily?

Can anyone assist me in figuring out how to add a file of type Express.Multer.File into a FormData object? Situation: I have received a file with the type Express.Multer.File (I am using nestjs and followed this part of the documentation: https://docs.nes ...

Creating default selection in angular 6 using formControlName in a dropdown menu

I am currently learning MEAN stack with Angular 6 and I have a question regarding selecting the default value in a dropdown using formControlName. When updating a form, I need to have a default value in my dropdown list but I'm only getting a blank op ...

Book Roulette: Your Next Random Read

I created a code for a random quote generator and now I want to create something similar, but with images this time. I am looking to add a feature on my page where it can recommend a book by displaying its cover image when a button is clicked. For the pre ...

Tips for showing an Object with nested Objects in Vue.js

Looking for guidance on displaying a JSON object in Vue.js with the following structure: { "1": [ "15-16", "16-17", "17-18", "18-19" ], "2": [ & ...

Refreshing data causes the data to accumulate and duplicate using the .append function in Jquery

I am currently working with a dynamic table that is being populated using AJAX and jQuery. Everything seems to be functioning correctly, however, I am encountering an issue when trying to reload the data as it just continues to stack up. Below is the func ...

Following a server reboot, an authenticated user will be logged out

I am facing an issue with my Node application where users are getting logged out whenever I update or edit a .js file. The application uses passport-local along with express.io and also incorporates mongoose and socket.io. app.configure(function() { a ...

Determine the number of pending HTTP requests

Currently, I am developing a highly demanding web server using node.js. I would like to implement a feature in my server code that tracks the number of http requests awaiting processing every second. Can this functionality be achieved in node.js? By the w ...

Dynamic content loading in Angular through HTML upon clicking

In the process of developing an Angular store, I aim to create anchor tags for each product so that clicking on a tag will display the selected product information in an HTML template below. Below is the current code snippet: (function() { var app = an ...

Generate an adjustable grid layout (with rows and columns) to display information retrieved from an API request

I have recently started learning React JS and JavaScript. To practice, I am working on a small project where I am facing an issue with creating dynamic rows and columns. My aim is to display data in 4 columns initially and then move to a new row and column ...

Troubleshooting Issues with Implementing JavaScript for HTML5 Canvas

I've encountered an issue with my code. After fixing a previous bug, I now have a new one where the rectangle is not being drawn on the canvas. Surprisingly, the console isn't showing any errors. Here's the snippet of code: 13. var can ...

Extracting key values from JSON using Node.js

Trying to read a json file using nodejs and locating a specific key within the object is my current task: fs.readFile('./output.json', 'utf8', function(err, data) { if (err) throw err; console.log(Object.keys(data)); } ...

What is the best way to sort an array based on a person's name?

I have a list of different groups and their members: [ { "label": "Group A", "fields": [ { "value": "color1", "name": "Mike" }, { &quo ...

Is it possible to change button behavior based on input values when hovering?

Currently, I am attempting to create a webpage where users can input two colors and then when they press the button, a gradient of those two colors will appear on the button itself. <!doctype html> <html> <head> <script src=&apos ...