mongoose schema
const mongoose = require('mongoose');
require('mongoose-type-url');
const mobilesSchema = new mongoose.Schema({
name:{
type: String,
required: true,
trim: true,
maxLength:100
},
price:{
type: Number,
required: true
},
desc:{
type: String,
required: true,
trim: true
},
productLink:{type: mongoose.SchemaTypes.Url},
imageLink:{type: mongoose.SchemaTypes.Url},
}, {timestamps: true})
const Mobiles = mongoose.model('Mobiles', mobilesSchema)
module.exports = Mobiles
controller
const Mobiles = require('../models/mobiles')
exports.createMobile = async (req, res) => {
const {
name,
price,
desc,
productLink,
imageLink
} = req.body;
try{
const newMobile = new Mobiles();
newMobile.name = name;
newMobile.price = price;
newMobile.desc = desc;
newMobile.productLink = productLink;
newMobile.imageLink = imageLink;
await newMobile.save();
res.json({
successMessage: `${newMobile.name} added successfully`,
})
}catch(e){
console.log(e)
res.status(500).json({
errorMessage: 'Mobile creation failed',
})
}
}
routes
const express = require('express');
const router = express.Router();
const mobileController = require('../controllers/mobiles')
const {authenticateJWT} = require('../middleware/authenticator')
router.post('/', authenticateJWT, mobileController.createMobile );
router.get('/', authenticateJWT, mobileController.readMobile)
module.exports = router;
API
import axios from 'axios';
export const createMobile = async(data)=>{
const response = await axios.post('/api/mobiles', data)
return response;
}
Server.js
const express = require('express');
const app = express();
const cors = require('cors');
const connectDB = require('./database/db');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const authRoutes = require('./routes/auth');
const categoryRoutes = require('./routes/category');
const mobileRoutes = require('./routes/mobiles')
const port = process.env.PORT || 5000
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
app.use(cookieParser())
connectDB();
app.use('/api/auth', authRoutes);
app.use('/api/category', categoryRoutes);
app.use('/api/mobiles', mobileRoutes)
app.listen(port, () =>{
console.log(`Listening on port ${port}`)
})
Client-side
import React, {useState} from 'react'
import isEmpty from 'validator/lib/isEmpty';
import {createMobile} from '../../api/mobiles'
import '../../../node_modules/bootstrap/dist/css/bootstrap.min.css'
import {Collapse, Button} from 'react-bootstrap'
import { AlertMSG, SuccessMsg } from '../../helpers/message'
import {Loader} from '../../helpers/loader'
import {FaPlus} from 'react-icons/fa'
const AddMobile = () => {
const [loading, setLoading] = useState(false)
const [mobile, setMobile] = useState('')
const [errorMessage, setErrorMessage] = useState('')
const [successMessage, setSuccessMessage] = useState('')
const [mobileData, setMobileData] = useState({
name:'',
price:'',
desc:'',
productLink:'',
imageLink:''
})
const {
name,
price,
desc,
productLink,
imageLink
} = mobileData
const handleShow = () => setMobile(!mobile);
const handleMobileChange = evt => {
setErrorMessage('')
setSuccessMessage('')
setLoading(false)
setMobileData({
...mobileData,
[evt.target.name] : evt.target.value,
})
}
const handleMessage = evt => {
setErrorMessage('');
setSuccessMessage('');
}
const handleMobileSubmit = evt => {
setErrorMessage('');
setSuccessMessage('');
evt.preventDefault();
if (isEmpty(name)){
setErrorMessage('Name cannot be empty');
}else if(isEmpty(price)){
setErrorMessage('Price cannot be empty');
}else if(isEmpty(desc)){
setErrorMessage('Description cannot be empty');
}else if(isEmpty(productLink)){
setErrorMessage('Product Link cannot be empty');
}else if(isEmpty(imageLink)){
setErrorMessage('Image Link cannot be empty');
}else{
let formData = new FormData();
formData.append('name', name);
formData.append('price', price)
formData.append('desc', desc)
formData.append('productLink', productLink)
formData.append('imageLink', imageLink)
createMobile(formData)
.then((response) => {
setMobileData({
name:'',
price:'',
desc:'',
productLink:'',
imageLink:''
})
setSuccessMessage(response.data.successMessage)
})
.catch(err => {
setErrorMessage(err.response.data.errorMessage)
})
}
}
return(
<>
<div className=" my-2" onClick={handleMessage}>
<div className="container">
<div className="row pb-3">
<div className="col-md-12 my-2">
<Button color="success" className="btn btn-block" onClick={handleShow} style={{ marginBottom: '1rem' }}><FaPlus/> Add Mobile</Button>
<Collapse in={mobile}>
<div className="modal-dialog modal-dialog-centered modal-lg">
<div className="modal-content">
<form onSubmit={handleMobileSubmit}>
<div className="modal-header bg-success text-white">
<h5 className="modal-title"><FaPlus/> Add Mobile</h5>
</div>
<div className="modal-body my-2">
{errorMessage && AlertMSG(errorMessage)}
{successMessage && SuccessMsg(successMessage)}
{loading ?(
<div className='text-center'>{Loader()}</div>
):(
<>
<div className='form-group mb-2'>
<label className='text-secondary'>Mobile Name</label>
<input type='text' className='form-control' name='name' value={name} onChange={handleMobileChange}/>
</div>
<div className='form-group mb-2'>
<label className='text-secondary'>Mobile Price</label>
<input type='text' className='form-control' name='price' value={price} onChange={handleMobileChange}/>
</div>
<div className='form-group mb-2'>
<label className='text-secondary'>Mobile Description</label>
<input type='text' className='form-control' name='desc' value={desc} onChange={handleMobileChange}/>
</div>
<div className='form-group mb-2'>
<label className='text-secondary'>Product Link</label>
<input type='text' className='form-control' name='productLink' value={productLink} onChange={handleMobileChange}/>
</div>
<div className='form-group mb-2'>
<label className='text-secondary'>Image Link</label>
<input type='text' className='form-control' name='imageLink' value={imageLink} onChange={handleMobileChange}/>
</div>
</>
)}
</div>
<div className="modal-footer">
<button type="submit" className="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
</Collapse>
</div>
</div>
</div>
</div>
</>
);
}
export default AddMobile;
error is showing that
Error: Mobiles validation failed: name: Path name
is required., price: Path price
is required., desc: Path desc
is required.
at ValidationError.inspect
(E:AffiliateElect1Nucleusserver
ode_modulesmongooseliberrorvalidation.js:47:26)
at formatValue (internal/util/inspect.js:731:31)
at inspect (internal/util/inspect.js:295:10)
at formatWithOptionsInternal (internal/util/inspect.js:1958:40)
at formatWithOptions (internal/util/inspect.js:1842:10)
at Object.value (internal/console/constructor.js:306:14)
at Object.log (internal/console/constructor.js:341:61)
at exports.createMobile (E:AffiliateElect1Nucleusservercontrollersmobiles.js:17:17)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
errors:
name: ValidatorError: Path `name` is required.
at validate (E:AffiliateElect1Nucleusserver
ode_modulesmongooselibschematype.js:1235:13)
at E:AffiliateElect1Nucleusserver
ode_modulesmongooselibschematype.js:1218:7
at Array.forEach (<anonymous>)
at SchemaString.SchemaType.doValidate (E:AffiliateElect1Nucleusserver
ode_modulesmongooselibschematype.js:1163:14)
at E:AffiliateElect1Nucleusserver
ode_modulesmongooselibdocument.js:2505:18
at processTicksAndRejections (internal/process/task_queues.js:75:11)
properties: [Object],
kind: 'required',
path: 'name',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
price: ValidatorError: Path `price` is required.
at validate (E:AffiliateElect1Nucleusserver
ode_modulesmongooselibschematype.js:1235:13)
at E:AffiliateElect1Nucleusserver
ode_modulesmongooselibschematype.js:1218:7
at SchemaNumber.SchemaType.doValidate (E:AffiliateElect1Nucleusserver
ode_modulesmongooselibschematype.js:1163:14)
at E:AffiliateElect1Nucleusserver
ode_modulesmongooselibdocument.js:2505:18
at processTicksAndRejections (internal/process/task_queues