简体   繁体   中英

Mongoose find() method not working with query parameters

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.stack.imgur.com/7svLJ.png [2]: https://i.stack.imgur.com/ZgxRa.png

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' },...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM