Home > Software engineering >  Can not retrive user from mongodb using findOne
Can not retrive user from mongodb using findOne

Time:11-03

I am making a simple Walk-In register app where i will register a customer and then find that specific customer by their phone number. The registration part is done but i cannot get a customer by their phone number. A little help will be very much appreciated. Below im posting both my backend and frontend code.

API-Server.js

const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const cors = require('cors')
const customerRouter = require('./routes/customer');

const app = express();
const port = process.env.PORT || 5000;
dotenv.config();
app.use(cors())
app.use(express.json());
app.use('/api/customer', customerRouter);

mongoose
    .connect(process.env.MONGO_URI)
    .then((data) => {
        console.log(
            'MongoDb connected successfully....'
        );
    })
    .catch((err) => {
        console.log(err);
    });

app.listen(port, () => {
    console.log(`Server is running at Port ${port}`);
});

API - customerRoute.js

const router = require('express').Router();
const Customer = require('../models/Customer');

router.post('/add', (req, res) => {
    const newCustomer = new Customer({
        name: req.body.name,
        phone: req.body.phone,
        address: req.body.address,
        pin: req.body.pin,
    });
    newCustomer
        .save()
        .then((cx) => {
            if (!cx) {
                res
                    .status(400)
                    .send('Error creating a new customer');
            } else {
                res.send(cx);
            }
        })
        .catch((err) => {
            res.status(500).json({ err });
        });
});

router.get('/', (req, res) => {
    Customer.find()
        .then((cx) => {
            if (!cx) {
                res
                    .status(400)
                    .send('Error getting customer');
            } else {
                res.send(cx);
            }
        })
        .catch((err) => {
            res.status(500).json({ err });
        });
});

router.get('/getbyphone', (req, res) => {
    Customer.findOne({ phone: req.body.phone })
        .then((cx) => {
            if (!cx) {
                res
                    .status(400)
                    .send('Error getting customer');
            } else {
                res.send(cx);
            }
        })
        .catch((err) => {
            res.status(500).json({ err });
        });
});

router.get('/getbyname', (req, res) => {
    Customer.findOne({ name: req.body.name })
        .then((cx) => {
            if (!cx) {
                res
                    .status(400)
                    .send('Error getting customer');
            } else {
                res.send(cx);
            }
        })
        .catch((err) => {
            res.status(500).json({ err });
        });
});

module.exports = router;

Frontend - App.js

import { BrowserRouter as Router } from 'react-router-dom';
import { Route } from 'react-router-dom';
import Navbar from './components/Navbar';
import Search from './components/Search';
import Submit from './components/Submit';
function App() {
    return (
        <Router>
            <div className='App'>
                <Navbar />
                <Route path='/' exact component={Submit} />
                <Route path='/view' component={Search} />
            </div>
        </Router>
    );
}

export default App;

frontend - search.js

import axios from 'axios';
import React, { Component } from 'react';

export default class Search extends Component {
    constructor() {
        super();
        this.state = {
            phone: '',
        };
    }

    onPhoneChange = (event) => {
        this.setState({
            phone: event.target.value,
        });
    };

    handleSubmit = (event) => {
        event.preventDefault();

        console.log(this.state.phone);

        axios
            .get(
                'http://localhost:5000/api/customer/getbyphone',
                this.state.phone
            )
            .then((res) => {
                console.log(res.data);
            })
            .catch((err) => {
                console.log(err);
            });
        this.setState({
            phone: '',
        });
    };

    render() {
        return (
            <div>
                <h3>Search for a Customer</h3>
                <form
                    onSubmit={this.handleSubmit}
                    className='form-control form-control-sm'>
                    <div className='form-group'>
                        <label>Phone: </label>
                        <input
                            type='text'
                            required
                            className='form-control'
                            onChange={this.onPhoneChange}
                            value={this.state.phone}
                        />
                    </div>
                    <div className='form-group'>
                        <input
                            type='submit'
                            className='btn btn-primary'
                            value='Search Customer'
                        />
                    </div>
                </form>
            </div>
        );
    }
}

CodePudding user response:

you could change this route and read phone number from params

router.get('/getbyphone/:phone', (req, res) => {
    Customer.findOne({ phone: req.params.phone }) // change this line
        .then((cx) => {
            if (!cx) {
                res
                    .status(400)
                    .send('Error getting customer');
            } else {
                res.send(cx);
            }
        })
        .catch((err) => {
            res.status(500).json({ err });
        });
});

and change the react part like this

handleSubmit = (event) => {
    event.preventDefault();

    console.log(this.state.phone);

    axios
        .get(
            'http://localhost:5000/api/customer/getbyphone' this.state.phone /// change this line
        )
        .then((res) => {
            console.log(res.data);
        })
        .catch((err) => {
            console.log(err);
        });
    this.setState({
        phone: '',
    });
};
  • Related