Having Issues with Writing Backend Code in Express and Connecting To React

Viewed 52

I'm writing a code for creating a group within a website. And I'm using MongoDB as my database, but as a beginner, it's hard for me to understand the API that they provide. So basically, I'm having issues with connecting the backend to the frontend when I'm trying to create a group for my website. This is the backend code for create_group

router.post('/create_group', (req, res) => {
    try {
        const newGroup = Group.create(req.body);

        res.status(201).json({
            data: {
                Groups:
                    newGroup
            }
        });
    } catch (err) {
        res.status(400).json({
            status: 'fail',
            message: err
        });
    }
  //res.json(database.groups[database.groups.length-1]);

As you can see, I want to write a code that's appropriate for MongoDB that looks like the portion that I commented out. I want to return the object that I just saved so I can display that information in when I change the route. The frontend code looks like this:

 onSubmitCreate = () => {
        fetch('http://localhost:3000/groups/create_group', {
            method: 'post',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                name: this.state.name,
                description: this.state.description,
                members: 1,
                likes: 0
            })
        })
            .then(response => response.json())
            .then(group => {
                if (group) {
                    //this.props.loadUser(user);
                    console.log('this is what Im working on' + group.name);
                    this.props.onCreateGroup(group);


                }
            });
    }

In the frontend, as I make a request to post the information to the database, I want to read the response and work with that information. But when I console.log the group variable, I just get an empty object as a response and I don't know how to make it return the information that the user typed in. And in case you want to see what onCreateGroup fucntion looks like, here it is.

    const onCreateGroup = (group) => {
        setGroupInfo({
            name: group.name,
            description: group.description,
            likes: 0,
            members: 1
        });
        setRoute('group_page');
    }

Please help me! Thank you in advance!

Edit: I was requested to post js file where I import express so I'm posting it here

const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
mongoose.connect("mongodb+srv://teamboogle:wMKsYJNhTfL89k9@cluster0.nhcrc.mongodb.net/TalkWithMe?retryWrites=true&w=majority", { useNewUrlParser: true });

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const profileRouter = require('./routes/profile');
const postsRouter = require('./routes/posts');
const groupsRouter = require('./routes/groups');
const signinRouter = require('./routes/signin');
const registerRouter = require('./routes/signin');






var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(cors());
app.use(bodyParser.json());

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/profile', profileRouter);
app.use('/posts', postsRouter);
app.use('/groups', groupsRouter);
app.use('/signin', signinRouter);
app.use('/register', registerRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function(){
  console.log('Connection Secured');
})

module.exports = app;

1 Answers

You are not saving the object in MongoDB properly, and you also need to return the object that you saved in Group collection as well.

Also, since you are returning data.Groups.group, you need to read that in the response as well

Please try this:

router.post('/create_group', async (req, res) => {
    try {
        const newGroup = new Group(req.body);
        let group = await newGroup.save()

        res.status(201).json({
            data: {
                Groups:
                    group//return the saved object
            }
        });
    } catch (err) {
        res.status(400).json({
            status: 'fail',
            message: err
        });
    }
}

In frontend code

onSubmitCreate = () => {
    fetch(...)
        .then(response => response.json())
        .then(data => {
            // read data.Groups.group from response
            let group = data.Groups.group
            if (group) {
                //this.props.loadUser(user);
                console.log('this is what Im working on' + group.name);
                this.props.onCreateGroup(group);


            }
        });
}
Related