search

Home  >  Q&A  >  body text

Problem: When using axios to POST data in MongoDB, only the ObjectId is returned and no other data is posted. Edited title: Axios POST request in MongoDB returns only ObjectId, other data is not posted.

I'm building a simple CRUD application using the MERN stack Below is the code to add user details in db

import React , {useState, useEffect} from 'react'
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

const initialValue = {
  name: '',
  username: '',
  email: '',
  phone: ''
}

const AddUser = () => {
// hooks
const [user, setUser] = useState(initialValue);
const { name, username, email, phone } = user; 

let navigate = useNavigate();
const onValueChange = (e) => {
    setUser({...user, [e.target.name]: e.target.value})
}

// ADD USER
const config = {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
}

const addUser = async (user) => {
  return await axios.post("http://localhost:5000/add", user , config);
}
const addUserDetails = async() => {
    await addUser(user);
    navigate('/all');
}

  return (
    <div>
      <h1>Add Details</h1>
      <form className="form">
      <input onChange={(e) => onValueChange(e)} placeholer="Add Name"name='name' value={name} id="my-input" />
      <input onChange={(e) => onValueChange(e)} placeholer="Add Username"name='username' value={username} id="my-input" />
      <input onChange={(e) => onValueChange(e)} placeholer="Add Email"name='email' value={email} id="my-input" />
      <input onChange={(e) => onValueChange(e)} placeholer="Add Phone"name='phone' value={phone} id="my-input" />
      <button type="submit" onClick={() => addUserDetails()}>Add</button>
      </form>
    
    </div>
  )
}

export default AddUser

The following is a screenshot of mongodb

The following is Route.js

const router = require('express').Router();
    const User = require('../model/todoItems.js');
    
    // Coming from model
    
    // POST DATA
    router.post('/add',async (req,res) =>{
    
    try { 
      const newUser = new User({user: req.body.user});
    
      // saving in db
      await newUser.save();
      res.status(201).json(newUser);
      
    } catch (error) {
      res.status(409).json({ message: error.message});     
    }
    }
    );
    
    module.exports = router;

The following is the model

const mongoose = require( 'mongoose');


const userSchema = new mongoose.Schema({
  user:{
    name: String,
    username: String,
    email: String,
    phone: Number
  }
    
});

module.exports= mongoose.model('user', userSchema);

{_id:ObjectId(641548f49338e07c498bf231),__v:0} this is what i got Database connection successful. I want all details posted, what should I do?

P粉564301782P粉564301782266 days ago366

reply all(1)I'll reply

  • P粉178894235

    P粉1788942352024-02-22 16:50:51

    There are some errors in your code. I think the problem will be solved when you correct them.

    1-) Check that you have imported the correct model in route.js. Because it is todoItem.js. I think this must be user related.

    const User = require('../model/todoItems.js');

    2-) In mongoose models, there is no need to use user as parent. Just delete it so it looks like:

    const userSchema = new mongoose.Schema({
        name: String,
        username: String,
        email: String,
        phone: Number
    });

    3-) In route.js, change the const newUser line as follows:

    const newUser = new User(req.body);

    4-) Make sure to use console.log to get the correct req.body

    console.log("req.body: ", req.body);
    const newUser = new User(req.body);

    reply
    0
  • Cancelreply