In this articles will teach how to search records Node js React Express Mongodb.how the search functionality works.
Node Js as backend front end React.
Create the Node js Project using following command
npm init
Install the following dependencies
- npm i mongoose
- npm i express
- npm install –save-dev nodemon
Server.js
const express = require('express') const sever = express() const port = 4000 var routes = require('./routes/routes'); var mongoose = require('mongoose'); mongoose.set('strictQuery', true); mongoose.connect("mongodb://127.0.0.1:27017/dbschool",{useNewUrlParser: true, useUnifiedTopology: true },function checkDb(error) { if(error) { console.log(error); } else { console.log("successfully Connected to DB"); } }); sever.use(express.json()); sever.use(routes); sever.listen(port, () => { console.log(`Express port successfully ${port}`) })
routes.js
var express = require('express'); var userController = require('../src/employee/userController'); const router = express.Router(); router.route('/user/findOne/:name').get(userController.findOneUserController); module.exports = router;
userController.js
var userService = require('./userService');
var findOneUserController = async (req, res) =>
{
console.log(req.params.name );
var result = await userService.findOneUserDBService(req.params.name );
if (result) {
res.send({ "status": true, "data": result} );
} else {
res.send({ "status": false, "data": "User not found" });
}
}
module.exports = { findOneUserController};
userModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: {
type: String,
required: true
},
address: {
type: String,
required: true
},
phone: {
type: String,
required: true
}
});
module.exports = mongoose.model('employees', userSchema);
userService.js
var userModel = require('./userModel'); module.exports.findOneUserDBService = (userDetais) => { return new Promise(function myFn(resolve, reject) { userModel.findOne({name:userDetais}, function returnData(error, result) { if(error) { reject(false); } else { resolve(result); } }); }); }
React
React is a front-end application we have already created the folder front end inside the folder open the command prompt and type the commands.
Installing React
npx create-react-app front-end
After that you need to install the required dependencies
npm install --save axios
For managing the Api requests
2.npm i react-router-dom
For managing the routes
After that go to the bootstrap webite and copy the bootstap css style and paste inside the
index.html inside the head tag.
Search.js
import axios from "axios"; import { useState } from "react"; function Search() { const [name, setName] = useState(""); const [address, setAddress] = useState(""); const [phone, setPhone] = useState([]); async function search(event) { event.preventDefault(); try { axios.post("http://localhost:4000/user/findOne/" + name ).then((res) => { console.log(res.data); if (res.data.data =="User not found") { alert("User not found"); setAddress(""); setPhone(""); } else { setAddress(res.data.data.address); setPhone(res.data.data.phone); } }, fail => { console.error(fail); // Error! }); } catch (err) { alert(err); } } return ( <div> <h1 align="center">Student Details</h1> <div class="container mt-4"> <form> <div class="form-group"> <div class="alert alert-danger" role="alert"> <label>Student Name</label> <input type="text" class="form-control" id="name" value={name} onChange={(event) => { setName(event.target.value); }} /> </div> </div> <button class="btn btn-primary mt-4" onClick={search}> Search </button> </form> <br/> <div class="container"> <div class="card"> <div class="alert alert-primary" role="alert"> <div class="form-group"> <label>Address</label> <input type="text" class="form-control" id="address" value={address} onChange={(event) => { setAddress(event.target.value); }} /> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" id="phone" value={phone} onChange={(event) => { setPhone(event.target.value); }} /> </div> </div> </div> </div> </div> </div> ); } export default Search;
App.js
import Search from "./components/Search"; function App() { return ( <div> <Search/> </div> ); } export default App;