I want to add a user to my database. But I couldn't add a user.I played on the user schema as much as I could, but I still couldn't get a record in the database. What should I do?
//routes/user.js
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('config');
const User=require('../models');
const { check, validationResult } = require('express-validator');
const User = require('../models/User');
// #route POST api/users
// #dsc Register a user
// #access Public
router.post(
'/',
[
check('name', 'Please add a name').notEmpty(),
check('email', 'Please include a valid email').isEmail(),
check(
'password',
'Please Enter a password for 6 or more characters'
).isLength({ min: 6 }),
check('address', 'Please include a valid address').notEmpty(),
check('location', 'Please include a valid location').notEmpty(),
check('phone', 'Please include a valid number').isLength(10),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, password, address, location, phone } = req.body;
try {
let user = await User.findOne({ email });
if (user) {
return res.status(400).json({ msg: 'User already exists' });
}
user = new User({
name,
email,
password,
address,
location,
phone,
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
const payload = {
user: {
id: user.id,
},
};
jwt.sign(
payload,
config.get('jwtSecret'),
{
expiresIn: 3600000,
},
(err, token) => {
if (err) throw err;
res.json({ token: token, userId: user.id }rot);
}
);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
}
);
module.exports = router;
//frontend user.js
import React, { Component } from "react";
import { Redirect, Link } from "react-router-dom";
import Home from "./Home";
import "./signup.css";
import img from "./cart-removebg-preview.png";
import img1 from './WhatsApp Image 2020-09-18 at 17.35.32.jpeg';
import Axios from "axios";
import { localsName } from "ejs";
class Signup extends Component {
constructor(props) {
super(props);
this.signup = this.signup.bind(this);
this.handleChange = this.handleChange.bind(this);
this.state = {
email: "",
password: "",
name: "",
phone: "",
address: "",
location: "",
valid: false,
userId: "",
};
}
signup = async (e) => {
e.preventDefault();
await Axios.post("/api/users", {
name: this.state.name,
email: this.state.email,
password: this.state.password,
address: this.state.address,
location: this.state.location,
phone: this.state.phone,
})
.then((res) =>
this.setState({ valid: res.data.token, userId: res.data.userId })
)
.catch((err) => console.log(err));
};
handleChange(e) {
this.setState({
[e.target.name]: e.target.value,
});
}
render() {
if (this.state.valid) {
localStorage.setItem("token", this.state.valid);
localStorage.setItem("userId", this.state.userId);
}
if (this.state.valid) return <Redirect to="/"></Redirect>;
return (
<div className='signup'>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="/">Stud-Shop</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li className="nav-item">
<i className="fas fa-home"></i>
</li>
<li className="nav-item">
Login
</li>
</ul>
</div>
</nav>
<img src={img} className='mobSignup'/>
<div className="row">
<div className="col-lg-3 bg-white rounded ">
<div className='card'>
<form>
<div className="form-group">
<h3>Sign-Up</h3>
<label htmlFor="exampleInputEmail1"><i class=" fa-lg fas fa-envelope"></i></label>
<input
type="email"
name="email"
className="form-control"
aria-describedby="emailHelp"
placeholder="Email-Address"
value={this.state.email}
onChange={this.handleChange}
></input>
<small className="form-text text-muted">
we'll never share your email with anyone!
</small>
<label><i class=" fa-lg fas fa-key"></i></label>
<input
value={this.state.password}
name="password"
type="password"
placeholder="Password (Min Length-6)"
className="form-control"
aria-describedby="emailHelp"
onChange={this.handleChange}
></input>
<label><i class=" fa-lg fas fa-user"></i></label>
<input
type="text"
name="name"
className="form-control"
placeholder="Name"
aria-describedby="emailHelp"
onChange={this.handleChange}
value={this.state.name}
></input>
<label><i class=" fa-lg fas fa-phone"></i>.</label>
<input
value={this.state.phone}
name="phone"
type="Number"
placeholder="Ph No. (Ex-98765XXXXX)"
className="form-control"
aria-describedby="emailHelp"
onChange={this.handleChange}
></input>
<label><i class=" fa-lg fas fa-home"></i></label>
<input
value={this.state.address}
type="text"
name="address"
className="form-control"
placeholder="Address"
aria-describedby="emailHelp"
onChange={this.handleChange}
></input>
<label><i class=" fa-lg fas fa-map-marked"></i></label>
<input
value={this.state.location}
type="text"
name="location"
className="form-control"
placeholder="Location (City)"
aria-describedby="emailHelp"
onChange={this.handleChange}
></input>
</div>
<button
type="submit"
onClick={this.signup}
className="btn btn-primary"
>
Sign-Up <i className=" fas fa-check"></i>
</button>
</form>
</div>
</div>
<div className='col-lg-8'>
<img src={img} className='signupImg'/>
</div>
</div>
</div>
);
}
}
export default Signup;
//model.js
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
name: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
location: {
type: String,
required: true,
},
phone: {
type: Number,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},},
{
collection:"Users"}
);
const model = mongoose.model('UserSchema', UserSchema)
module.exports = model
database connection is established. I tried to get the code from outside, but when I tried it with my code, it didn't work. What should I do? Can you help me?
Related
I am trying to fetch data from client side when i make a post request I get this error , I am new to the mongoDB and Node.js please help
I don't understand this error that why this is coming please help to resolve it
this is my schema code
`
import mongoose from "mongoose";
const signupTemplate = mongoose.Schema({
Name: {
type: String,
required: true,
},
Phone: {
type: Number,
required: true,
},
Email: {
type: String,
required: true,
},
Password: {
type: String,
required: true,
},
date: {
type: Date,
Default: Date.now,
},
});
export default mongoose.model("users", signupTemplate);
`
this is my router code
`
router.post("/signup", (req, res) => {
const signedUpUser = new signUpTemplate({
Name: req.body.Name,
Phone: req.body.Phone,
Email: req.body.Email,
Password: req.body.Password,
});
console.log(req.body.Name);
signedUpUser
.save()
.then((data) => {
res.json(data);
})
.catch((err) => {
res.json(err);
// console.log('you made an error');
});
// res.send("User Registered successfully");
});
`
this is my form code
`
<form action="/signup" method="post">
<label for="Name">Full Name</label>
<input type="text" class="form-control" id="Name" name="Name" />
<label for="Phoneno">Phone No.</label>
<input type="text" class="form-control"id="Phoneno" name="Phone" />
<label for="Email">Email</label>
<input type="email" class="form-control"id="Email" name="Email" />
<label for="create-password">Create Password</label>
<input type="password" class="form-control"id="create-password" name="Password" />
<label for="confirm-password">Confirm Password</label>
<input type="password" class="form-control"id="confirm-password" name=" Confirm-password" />
<button type="submit" class="btn">Sign Up</button>
<hr>
<p style="display:inline;">Or continue with</p>
<i class="fa-brands fa-google"></i>
<i class="fa-brands fa-facebook"></i>
<i class="fa-brands fa-instagram"></i>
</form>
`
Hey do you have the express urlencoded middleware in your index.js or server.js and if not add this line of code
app.use(express.urlencoded({ extended: true }));
The code works well and perfectly when i use Postman to make the requests. But whenever I send the same request from the frontend I get this error.
Result {
formatter: [Function: formatter],
errors: [
{
value: undefined,
msg: 'Please enter your name',
param: 'name',
location: 'body'
},
{
value: '',
msg: 'Please enter a valid Email',
param: 'email',
location: 'body'
},
{
value: undefined,
msg: 'Please enter a password with 6 or more characters',
param: 'password',
location: 'body'
}
]
}
Here is my signup.ejs file.
<!doctype html>
<html lang="en">
<%- include('./partials/header.ejs')%>
<%- include('./partials/navbar.ejs')%>
<body>
<section class="form my-4 mx-5">
<div class="container">
<div class="row no-gutter">
<div class="col-lg-5">
<img src="/images/joyce-busola-Nnv0DHFG1Ds-unsplash.jpg" class="img-fluid">
</div>
<div class="col-lg-7 px-5 pt-5">
<h1 class="font-weight-bold py-3">Queue's</h1>
<h4>Register your new Account</h4>
<form action="/user/register" method="POST">
<div class="form-row">
<div class="col-lg-7">
<input type="text" id="name" class="form-control my-3 p-3" placeholder="your name">
</div>
</div>
<div class="form-row">
<div class="col-lg-7">
<input type="email" id="email" class="form-control my-3 p-3" placeholder="email address">
</div>
</div>
<div class="form-row">
<div class="col-lg-7 input-group">
<input type="password" class="form-control my-3 p-3" id="password" placeholder="password">
<div class="input-group-addon my-3 p-3">
</a><i class="bi bi-eye-slash" id="togglePassword"></i>
</div>
</div>
</div>
<div class="form-row">
<div class="col-lg-7">
<button type="submit" class="btn1 mt-3 mb-5">Register</button>
</div>
</div>
forgot password
<p>Already have an acount? Login here</p>
</form>
</div>
</div>
</div>
</section>
<%- include('./partials/footer.ejs')%>
</body>
</html>
Here is a copy of my signup controller object.
require('dotenv').config();
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const { createToken } = require('../middleware/auth_middleware');
const maxAge = 36000;
module.exports.register_post = async (req, res) => {
const { name, email, password } = req.body;
// Searching if User already exists
try {
let user = await User.findOne({ email });
if(user) return res.status(400).json({ errors : [{ msg: "User already exists"}],});
// Create User Object
user = new User({ name, email, password });
// Saving new User
await user.save();
// Creating User token with JWT
let payLoad = user._id;
const prize = createToken(payLoad);
res.cookie('jwt', prize, {
httpOnly: true,
maxAge : maxAge * 1000
});
res.status(201).json({
msg: `${user.email} successfully registered`,
name: user.name,
email: user.email});
console.log(user, prize);
}
catch (error) {
console.log(error.message);
res.status(500).send('Server error')
};
}
I made a middleware to handle validations with express-validator. Here is the validator file.
require('dotenv').config()
const { check, validationResult } = require('express-validator');
const jwt = require('jsonwebtoken');
const maxAge = 36000;
const secret = process.env.JWT_SECRET;
const authValidator = () => {
return [
check('name', 'Please enter your name').not().isEmpty(),
check('email', 'Please enter a valid Email').trim().isEmail(),
check('password', 'Please enter a password with 6 or more characters').isLength({min:6})
]};
const validateError = (req, res, next) => {
const errors = validationResult(req);
if(errors.isEmpty()) {
return next()
}
const extractedErrors = [];
errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }))
console.log(errors);
return res.status(400).json({ errors: extractedErrors })
}
Here is the signup router file
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
const { authValidator, validateError } = require('../middleware/auth_middleware');
router.get('/login', userController.login_get );
router.post('/login', userController.login_post );
router.get('/register', userController.register_get );
router.post('/register', authValidator(), validateError, userController.register_post );
module.exports = router;
Your input fields lack the name field. That's why the input data is not found in the body of the request.
for example for the email field:
<div class="form-row">
<div class="col-lg-7">
<input type="email" name="email" id="email" class="form-control my-3 p-3" placeholder="email address">
</div>
</div>
I have a checkout page for a store that has some inputs such as address, name, etc. I also want to upload the cart info to the mongodb as well, but it's not working. The cart info comes from redux using the useSelector from redux, but I can't put that function into server.js. Does anyone have any tips? I have provided the schema below as well.
Server.js
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const connectDB = require('./config/db');
const productRoutes = require('./routes/productRoutes');
const CustomerInfo = require("./models/customerInfo");
connectDB();
const app = express();
app.use(express.json());
app.use('/api/products', productRoutes);
const PORT = process.env.PORT || 5000;
app.use(bodyParser.urlencoded({extended: true}));
//app.post
app.post ("/", function(req, res) {
let newCustomerInfo = new CustomerInfo({
fname: req.body.firstName,
lname: req.body.lastName,
email: req.body.email,
phone: req.body.phoneNumber,
address: req.body.address,
city: req.body.city,
district: req.body.district,
section: req.body.section,
confirmCode: req.body.confirmCode,
comments: req.body.extraInfo,
cartItems: req.body.cartcount
});
newCustomerInfo.save();
res.redirect("/");
})
app.listen(PORT, () => console.log(`Server Running on port ${PORT}`))
CheckoutScreen.js
import './CheckoutScreen.css';
import { useDispatch, useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
// Components
import CartItem from '../components/CartItem';
const CheckoutScreen = () => {
const cart = useSelector(state => state.cart);
const { cartItems } = cart;
const getCartCount = () => {
return cartItems.reduce((qty, item) => Number(item.qty) + qty, 0)
};
const getCartSubTotal = () => {
return cartItems.reduce((price, item) => item.price * item.qty + price, 0)
};
return (
<div className="checkoutscreen">
<div className="checkout__left">
<body>
<form className="checkout-form" method="post" action="/">
<label className="input">
<input type="text" name="firstName" required/>
<span className="placeholder">First Name</span>
</label>
<label className="input">
<input type="text" name="lastName" required/>
<span className="placeholder">Last Name</span>
</label>
<label className="input">
<input type="text" name="email" required/>
<span className="placeholder">Email</span>
</label>
<label className="input">
<input type="text" name="phoneNumber" required/>
<span className="placeholder">Phone Number</span>
</label>
<label className="input">
<input type="text" name="address" required/>
<span className="placeholder">Address</span>
</label>
<label className="input">
<input type="text" name="city" required/>
<span className="placeholder">City</span>
</label>
<label className="input">
<input type="text" name="district" required/>
<span className="placeholder">District</span>
</label>
<label className="input">
<input type="text" name="section" required/>
<span className="placeholder">Section</span>
</label>
<label className="input">
<input type="text" name="confirmCode" required/>
<span className="placeholder">Confirmation Code</span>
</label>
<label className="input">
<input type="text" name="extraInfo" required/>
<span className="placeholder">Details/Comments</span>
</label>
<p className="cartcount">{getCartCount()}</p>
<button>Submit</button>
</form>
</body>
</div>
<div className ="checkout__right">
<div className="checkout__info">
<p>Subtotal ({getCartCount()}) items</p>
<p>${getCartSubTotal().toFixed(2)}</p>
</div>
</div>
</div>
)
};
export default CheckoutScreen;
customerInfo.js
const mongoose = require("mongoose");
const customerInfoSchema = new mongoose.Schema ({
fname: {
type: String,
required: true
},
lname: {
type: String,
required: true
},
email: {
type: String,
required: true
},
phone: {
type: String,
required: true
},
address: {
type: String,
required: true
},
city: {
type: String,
required: true
},
district: {
type: String,
required: true
},
section: {
type: String,
required: true
},
confirmCode: {
type: String,
required: true
},
comments: {
type: String,
required: false
},
cartItems: {
type: Number,
required: true
}
});
const customerInfo = mongoose.model('Customer Info', customerInfoSchema);
module.exports = customerInfo;
You need to call your API in Server.js. To call the API you need to submit the form and handle the form submission by handleSubmit method on form onSubmit event. In handleSubmit method you need to call checkout action and pass the cart object. The CheckoutAction need to use redux-thunk to call server api asynchronously (side effect with middleware). Once the response back you can return the state by dispatching to CheckoutReducer
CheckoutScreen.js
import { Checkout } from '../action/checkoutAction'
const dispatch = useDispatch();
...........
const handleCheckout = e => {
e.preventDefault();
dispatch(Checkout({ type:'CHECKOUT', payload:cart }));
}
......
<form className="checkout-form" method="post" action="/" onSubmit={e => handleCheckout(e)}>
CheckoutAction.js
export const Checkout = data => async dispatch => {
let response = await axios.post(server_api_url, data);
dispatch({ type: 'checkout_success', payload:response.data}); //to checkout reducer
}
I am making a MERN application with register and login functionality. When i try to submit the form in the browser the console shows me a 400 bad request. The functionality works on the backend and returns a 200 ok status but not on the front-end.
dispatchXhrRequest # 0.chunk.js:610
xhrAdapter # 0.chunk.js:455
dispatchRequest # 0.chunk.js:1079
Promise.then (async)
request # 0.chunk.js:866
Axios.<computed> # 0.chunk.js:891
wrap # 0.chunk.js:1421
(anonymous) # main.chunk.js:445
(anonymous) # 0.chunk.js:44123
(anonymous) # 0.chunk.js:44631
Register.onSubmit # main.chunk.js:1073
callCallback # 0.chunk.js:12247
invokeGuardedCallbackDev # 0.chunk.js:12296
invokeGuardedCallback # 0.chunk.js:12356
invokeGuardedCallbackAndCatchFirstError # 0.chunk.js:12371
executeDispatch # 0.chunk.js:16606
processDispatchQueueItemsInOrder # 0.chunk.js:16638
processDispatchQueue # 0.chunk.js:16651
dispatchEventsForPlugins # 0.chunk.js:16662
(anonymous) # 0.chunk.js:16873
batchedEventUpdates$1 # 0.chunk.js:30558
batchedEventUpdates # 0.chunk.js:12045
dispatchEventForPluginEventSystem # 0.chunk.js:16872
attemptToDispatchEvent # 0.chunk.js:14355
dispatchEvent # 0.chunk.js:14273
unstable_runWithPriority # 0.chunk.js:45915
runWithPriority$1 # 0.chunk.js:19653
discreteUpdates$1 # 0.chunk.js:30575
discreteUpdates # 0.chunk.js:12057
dispatchDiscreteEvent # 0.chunk.js:14239
This is my controller code for my my Register functionality
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require ("jsonwebtoken");
const keys = require("../../config/key");
const validateRegisterInput = require("../../validation/register");
const validateLoginInput = require("../../validation/login");
const User = require("../../models/User");
router.post("/register", (req, res) => {
//FORM VALIDATION
const {errors, isValid } = validateRegisterInput(req.body)
//CHECK VALIDATION
if(!isValid) {
return res.status(400).json(errors)
}
User.findOne({ email: req.body.email }).then( returnedUser => {
if(returnedUser) {
return res.send(400).json({email: "Email already exists"});
}
});
// saving user with request information to database
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
bcrypt.genSalt(10, (err, salt)=>{
bcrypt.hash(newUser.password, salt, (err, hash)=>{
if(err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
});
This is my model for my userSchema
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
// const UserSchema = new Schema({
// name: {type: String, required: true},
// email: {type: String, required: true},
// password: {type: String, required: true},
// date: {type: Date, default: Date.now},
// // classwork: [classworkSchema],
// // outcomes: [OutcomesSchema],
// // meetups: [MeetupSchema],
// })
module.exports= User = mongoose.model("users", UserSchema);
Here is my register component.
import React, { Component } from "react";
import { Link, withRouter } from "react-router-dom";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { registerUser } from "../../actions/authActions";
import classnames from "classnames";
class Register extends Component {
constructor() {
super();
this.state = {
name: "",
email: "",
password: "",
password2: "",
errors: {},
};
}
componentDidMount() {
// If logged in and user navigates to Register page, should redirect them to dashboard
if (this.props.auth.isAuthenticated) {
this.props.history.push("/dashboard");
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
this.setState({
errors: nextProps.errors,
});
}
}
onChange = (e) => {
this.setState({ [e.target.id]: e.target.value });
};
onSubmit = (e) => {
e.preventDefault();
const newUser = {
name: this.state.name,
email: this.state.email,
password: this.state.password,
password2: this.state.password2,
};
console.log(newUser);
this.props.registerUser(newUser, this.props.history);
};
render() {
const { errors } = this.state;
return (
<div className="container">
<div className="row">
<div className="col s8 offset-s2">
<Link to="/" className="btn-flat waves-effect">
<i className="material-icons left">keyboard_backspace</i> Back to
home
</Link>
<div className="col s12" style={{ paddingLeft: "11.250px" }}>
<h4>
<b>Register</b> below
</h4>
<p className="grey-text text-darken-1">
Already have an account? <Link to="/login">Log in</Link>
</p>
</div>
<form noValidate onSubmit={this.onSubmit}>
<div className="input-field col s12">
<input
onChange={this.onChange}
value={this.state.name}
error={errors.name}
id="name"
type="text"
className={classnames("", {
invalid: errors.name
})}
/>
<label htmlFor="name">Name</label>
<span className="red-text">{errors.name}</span>
</div>
<div className="input-field col s12">
<input
onChange={this.onChange}
value={this.state.email}
error={errors.email}
id="email"
type="email"
className={classnames("", {
invalid: errors.email
})}
/>
<label htmlFor="email">Email</label>
<span className="red-text">{errors.email}</span>
</div>
<div className="input-field col s12">
<input
onChange={this.onChange}
value={this.state.password}
error={errors.password}
id="password"
type="password"
className={classnames("", {
invalid: errors.password
})}
/>
<label htmlFor="password">Password</label>
<span className="red-text">{errors.password}</span>
</div>
<div className="input-field col s12">
<input
onChange={this.onChange}
value={this.state.password2}
error={errors.password2}
id="password2"
type="password"
className={classnames("", {
invalid: errors.password2
})}
/>
<label htmlFor="password2">Confirm Password</label>
<span className="red-text">{errors.password2}</span>
</div>
<div className="col s12" style={{ paddingLeft: "11.250px" }}>
<button
style={{
width: "150px",
borderRadius: "3px",
letterSpacing: "1.5px",
marginTop: "1rem",
}}
type="submit"
className="btn btn-large waves-effect waves-light hoverable blue accent-3"
>
Sign up
</button>
</div>
</form>
</div>
</div>
</div>
);
}
}
Register.propTypes = {
registerUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
auth: state.auth,
errors: state.errors,
});
export default connect(mapStateToProps, { registerUser })(withRouter(Register));
here is the action
import axios from "axios";
import setAuthToken from "../utils/setAuthToken";
import jwt_decode from "jwt-decode";
import {
GET_ERRORS,
SET_CURRENT_USER,
USER_LOADING
} from "./types";
// Register User
export const registerUser = (userData, history) => dispatch => {
axios
.post("/api/users/register", userData)
.then(res => history.push("/login")) // re-direct to login on successful register
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
I am working on personal project. one of common functionality i am implementing is allowing users to update their profile but having hard time doing it.
here is what i did so far
form
<form
action="/users/doctor-profile?_method=PUT"
method="POST"
enctype="multipart/form-data"
>
<input type="hidden" name="_method" value="PUT" />
<div class="form-group">
<input
type="text"
class="form-control"
id="name"
name="name"
/>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input
type="tel"
class="form-control"
id="formGroupExampleInput"
name="phone"
/>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input
type="email"
class="form-control"
id="formGroupExampleInput"
name="email"
/>
</div>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
here is my user model
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
phone: {
type: String,
required: true,
},
});
const User = mongoose.model("User", UserSchema);
module.exports = User;
here is my post route
router.post("/users/doctor-profile", (req, res) => {
const { name, email,phone } = req.body;
const _id = ObjectId(req.session.passport.user._id);
console.log(_id)
USer.findOne({ _id: _id })
.then((user) => {
if (!user) {
req.flash("error_msg", "user not found");
res.redirect("/users/doctor-profile");
}
if (typeof name !== "undefined") {
user.name = name;
console.log(user.name);
}
if (typeof email !== "undefined") {
user.email = email;
}
if (typeof phone !== "undefined") {
user.phone = phone;
}
user.save().then((User) => {
req.flash("success_msg", "details updated successfully");
res.redirect("/users/profile");
});
})
.catch((err) => console.log(err));
});
console output
application running on port 5000
mongodb connection successfull
5ef5bc20261beb1e6c1c25a3
but it does not update fields in database.
try this:
user.save(function (err, resolve) {
if(err)
console.log('db error', err)
// saved!
});
You had a typo in your post route js file
here is the code you got the typo on:
USer.findOne({ _id: _id })
USer should be User