React / GraphQL - Cannot Submit to MongoDB. (MERNG STACK)

Hi everyone,

I’m doing this tutorial on YouTube to get reacquainted with React and learn GraphQL.

The issue arrises about 55 minutes in, when I go to submit a user to the database using the GraphQL playground I get this error: “message”: “Cannot read property ‘username’ of undefined”

I’ve gone through the video 3-4 times, copied it out exactly, left comments on what each bit of code does, googled it multiple times but I still can’t figure out what this issue is!

Also, I know that the server is connecting to the database.

File: “./graphQL/resolvers/users.js”

const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')

//Secret Key
const { SECRET_KEY } = require('../../config.js')
//MongoDB Schemas
const User = require('../../models/Users')

module.exports = {
  Mutation: {
    async register(
      _,
      {
        registerUser: { username, email, password, confirmPassword }
      },
      context,
      info
    ) {

      //VALIDATE USER DATA
      //MAKE SURE USER DOESN'T ALREADY EXIST
      //HASH USER PASSWORD
      //GIVE AUTH TOKEN

      //Take the password from the destructured registerUser method
      //inside async register function and encrypt the password.
      password = await bcrypt.hash(password, 12)


      //Create a new user using the models schema 
      //take the data from the other arguments in the register method.
      //use the date method and turn it into a string for the createdAt
      //field.
      const newUser = new User({
        email,
        username,
        password,
        createdAt: new Date().toISOString()
      })

      //Save new user to MongoDB
      const res = await newUser.save()

      //Create a token to authenticate our user using data from 
      //the above variable which we saved to Mongo
      //take the secret key from our config file and assign an 
      //expiration to the key
      const token = jwt.sign(
        {
          id: res.id,
          email: res.email,
          username: res.username,
        },
        SECRET_KEY, { expiresIn: '1h' }
      )

      //Return the data 
      return {
        ...res._doc,
        id: res._id,
        token
      }
    }
  }
}

File: “./graphQL/resolvers/index.js”

const postRes = require('./posts')
const userRes = require('./users')

module.exports = {
  Query: {
    ...postRes.Query
  },
  Mutation: {
    ...userRes.Mutation
  }
}

File: “./models/Users.js”

const { model, Schema } = require('mongoose');

const userSchema = new Schema({
  username: String,
  password: String,
  email: String,
  createdAt: String
});

module.exports = model('User', userSchema);

File: “./server.js”

const { ApolloServer } = require('apollo-server')
const mongoose = require('mongoose')

//typeDefs
const typeDefs = require('./graphQL/typeDefs')

//Resolvers to go fetch our data
const resolvers = require('./graphQL/resolvers')

//Used to connect to our database on MONGODB
const { MONGODB } = require('./config.js')

//Creating a new ApolloServer, ApolloServer uses Express in the background.
//Passing our server our types and our resolvers to use.
const server = new ApolloServer({
  typeDefs,
  resolvers
})

//Connect to MongoDB, and start listening on our port.
//useNewUrlParser to avoid deprecation warnings 
mongoose.connect(MONGODB, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    //Used to check connection to MongoDB
    console.log('MONGO DB CONNECTED')
    return server.listen({ port: 5000 })
  })
  .then(res => {
    console.log(mongoose.connection.readyState);
    console.log(`Server running at ${res.url}`)
  })

Please help, I’m getting dangerously close to losing it.

Bumping bumping bump?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.