Search code examples
mongodbserverstatemern

MongoDB returning blank object after POST request


I have an app I'm working on and I'm using MERN for the first time. When I use my POST method to try and create and object in my state, I get this response:

_id:61305018ed424fc0fa769dd7
__v:0

However, what I'm trying to get for example is:

movementName: squat,
movementWeight: 100

Here is my models/exerciseForm.js:

import mongoose from 'mongoose';

const movementSchema = mongoose.Schema({
    movementName: String,
    movementWeight: String,
});

export const ExerciseForm = mongoose.model('ExerciseForm', movementSchema);

my controllers/movements.js:

import { ExerciseForm } from '../models/exerciseForm.js';

export const fetchMovements = async (req,res) => {
    try {
        const postMovement = await ExerciseForm.find();

        res.status(200).json(postMovement);
    } catch(error) {
        res.status(404).json({ message: error.message })
    }
};

export const createMovement = async (req,res) => {
    const move = req.body;

    const newMove = new ExerciseForm(move);
    try {
        await newMove.save();

        res.status(201).json(newMove);
    } catch (error) {
        res.status(409).json({ message: error.message });
    }
};

here is my routes/movements.js

import express from 'express';
import { fetchMovements, createMovement } from '../controllers/movements.js';

const router = express.Router();

router.get('/', fetchMovements); 
router.post('/', createMovement); 

export default router;

here is my server/index.js (I am using my correct username/password):

import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import movementRoutes from './routes/movements.js';

const app = express();

app.use(cors());

app.use('/movements', movementRoutes)

const CONNECTION_URL = 'mongodb+srv://<username>:<password>@cluster0.z0e85.mongodb.net/myFirstDatabase?retryWrites=true&w=majority';
const PORT = process.env.PORT || 5000;

mongoose.connect( CONNECTION_URL )
    .then(() => app.listen(PORT, () => console.log(`Server running on port ${PORT}`)))
    .catch((error) => console.log(error.message));

I believe the error is somewhere in these files, aka my server. If everything here looks okay, then maybe it's in my actions,reducer, etc. and I'll try looking there.


Solution

  • install body-parser with npm and add these lines in your index file import

    import bodyParser from 'body-parser';
    app.use(bodyParser.json(extended: true }));