Search code examples
node.jsmongodbexpressmongoosepostman

How to get specific data from MongoDB in node js, using GET method?


I have some collections stored on a remote MongoDB server. I am trying to get a specific collection based on a city name. I am using POSTMAN to simulate a GET request, but a different GET method is being executed:

{
    message: "get is working!"
}

Here's the code:

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose'); 
const schema = require('../schemes/host_details');

router.get('/', (req, res, next)=>{
    res.status(200).json({
        message: 'get is working!'
    }); });

router.post('/', (req, res, next)=>{
    const host = new schema({
        _id: new mongoose.Types.ObjectId(),
        First_Name: req.body.f_name,
        Last_Name: req.body.l_name,
        State: req.body.state,
        City: req.body.city,
        Street_Address: req.body.st_address,
        Postal_Code: req.body.postal,
        Model_Make: req.body.model,
        Price: req.body.price,
        Lat: req.body.lat,
        Lng: req.body.lng
    });
    host.save().then(result=>{
        console.log(result);
    }) 
    .catch(err=>console.log(err));
    res.status(200).json({
        message: 'everthing will be ok, just hang in there!',
        createdHost: host
    }); });

router.get("/:city_name", (req, res, next)=>{

    const city_name_code = req.params.city_name;
    schema.findById(city_name_code).exec().then(doc=>{
        console.log(doc);
        res.status(200).json(doc);
    })
    .catch(err=>{console.log(err);
    res.status(500).json({error: err}); });

});

module.exports = router;

My App.js code-

const express=require('express');

const app=express();
var cors=require('cors'); 
const bodyParser=require('body-parser'); 
const mongoose=require('mongoose'); 
const host_details =require('./routes/host_details');


app.use(cors({origin:true,credentials:true}));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
mongoose.connect('mongodb+srv://xxx:xxxxxxxxxxxxxxxx.mt4xvth.mongodb.net/?retryWrites=true&w=majority&appName=xxxxxxxxxxxxxxx')


// app.use((req,res,next)=>{ 
//     res.status(200).json({ 
//         message:'abc' 
//     }); 
// });

app.use((req,res,next)=>{
    res.header("Access-Control-Allow-Origin","*");
    // res.header("Access-Control-Allow-Origin","Origin, X-Requested-With, Content-Type, Accept, Authorization");

    if(req.method==='OPTIONS')
    {
        res.header('Access-Control-Allow-Methods','PUT,POST,PATCH,DELETE');
        return res.status(200).json({});
    }
    next(); 
});


app.use('/hostdetails',host_details); 
module.exports= app;

POSTMAN_output


Solution

  • In Express there is a difference between req.query and req.params.

    You are trying to navigate to:

    http://www.example.com/hostdetails/?City=Dublin
    

    As far as Express is concerned you have mounted your router correctly but because you have:

    /?City=Dublin
    

    Then you are trying to implement a query string so that would be req.query.

    However you are using req.params here:

    const city_name_code = req.params.city_name;
    

    Solution:

    Send your postman requests to:

    http://www.example.com/hostdetails/Dublin
    

    Then in your code you need to search for City based on your schema :

    schema.findOne({City: city_name_code}).then(doc=>{
       console.log(doc);
       res.status(200).json(doc);
    })