1

I'm trying to find a particular document in mongodb using Node Js and mongoose .

But when I'm running following code snippet I'm getting no response from database.

const express = require("express");
const router = express.Router();
const Vehicle = require("../db/models/vehicle");

//api to get single vehicle data
router.get("/vehicle", async (req, res, next) => {
  try {
    const { name } = req.query;
    console.log(name);
    const vehicle = await Vehicle.find({ name: name });
    res.status(200).json(vehicle);
  } catch (error) {
    res.status(500).json({ message: error });
  }
});

[postman image with no response][1]

But when I'm running following code snippet I'm getting response from database.

const express = require("express");
const router = express.Router();
const Vehicle = require("../db/models/vehicle");

//api to get single vehicle data
router.get("/vehicle", async (req, res, next) => {
  try {
  
    const vehicle = await Vehicle.find({ name: "BMW II" });
    res.status(200).json(vehicle);
  } catch (error) {
    res.status(500).json({ message: error });
  }
});

[postman image with response][2] What should I do ? [1]: https://i.sstatic.net/7svLJ.png [2]: https://i.sstatic.net/ZgxRa.png

4
  • Maybe the the route path needs to be "/test/api/vehicle". Commented Feb 9, 2022 at 12:59
  • try removing the quotes from BMW II Commented Feb 9, 2022 at 13:04
  • In the first code snippet what does console.log(name); print? Do you actually get a valid name in your request? Commented Feb 9, 2022 at 13:07
  • yes i get name variable value which I pass in query string Commented Feb 9, 2022 at 14:10

1 Answer 1

1

As seen by this You are sending your query as name="BMW II" then in the server your name variable will be set to '"BMW II"' Therefore you will not get the correct results.

//your req will have a field like this
req = {query: { name: '"BMW II"' },...}

when sending query strings you do not enclose in quotes even though it is string. query strings in express are by default identified as strings in the backend.
just send in like name=BMW II and your name variable will be set to 'BMW II'.

req = {query: { name: 'BMW II' },...}

In case you are sending a number as a query string say num=5 Then in the backend you will have parse it to an integer if you are willing to do calculations on it since it is received as string from req.query

req = {query: { num: '5' },...}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.