首页 > 解决方案 > 无法使用 findOne 从 mongodb 检索用户

问题描述

我正在制作一个简单的步入式注册应用程序,我将在其中注册客户,然后通过他们的电话号码找到该特定客户。注册部分已完成,但我无法通过他们的电话号码获得客户。一点帮助将不胜感激。下面我发布了我的后端和前端代码。

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;

前端 - 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;

前端 - 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>
        );
    }
}

标签: node.jsreactjsmongodbexpress

解决方案


您可以更改此路线并从参数中读取电话号码

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 });
        });
});

并像这样更改反应部分

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: '',
    });
};

推荐阅读