0
votes

I am new to GraphQL and mongoose and trying to create a function in a resolver which creates a shawarma order, the inputs required are the shawarma ID, the quantity and an address, when I run the code typed below, I get an Error which states

TypeError: Cannot read property 'shawarmaOrdered' of undefined

the resolver code:

import mongoose from 'mongoose';
import AuthenticationError from 'apollo-server';
import {shawarma} from '../models/shawarmaModel';

export default {
    Query:{

    },
    Mutation: {
        createOrder: async(parent, {OrderInput}, {models: {orderModel, shawarmaModel}}, info) => {
            console.log('reached1')
            try{
                const {shawarmaOrdered, quantity, address} = OrderInput;
                const order = await orderModel.updateOne({shawarmaOrdered, quantity, address})
                return order
             

            } catch(err){
                console.log('errorr')
                console.log(err)
            }

        }
    },

    Order: {
        shawarmaOrdered: async(parent, {shawarmaOrdered}, {models:shawarmaModel}, info) =>{
            return shawarmaOrdered = shawarmaModel.find((shawarma)=>{
                return shawarma.id == parent.id
            })
        }
    }

the schema code:

import {gql} from 'apollo-server'

export default gql`

type Order{
    id: ID!
    shawarmaOrdered: Shawarma!
    quantity: Int 
    orderedTo: String
}

input OrderInput{
    shawarmaOrdered: ID!
    quantity: Int
    orderedTo: String
}


extend type Query {
    order(id: ID!): Order!
}


extend type Mutation {
        createOrder(shawarmaOrdered: String!, quantity: Int!, orderedTo: String!): Order!
}
`

the order model code:

import mongoose, { Mongoose } from 'mongoose'
import shawarma from './shawarmaModel'

const orderSchema = new mongoose.Schema({

    shawarmaOrdered: {
        type: mongoose.Schema.Types.ObjectId,
        ref: shawarma
    },
        
    quantity: {
        type: Number
    },

   completed: {
       type: Boolean,
       default: false
   }
})

const order = mongoose.model('order', orderSchema)
export default order;

kindly let me know if I'm doing something wrong

1
mutation argument name is dataxadm
Thanks for drawing it to my attention. I actually changed it but it still doesn't workalademerin
Check if your MongoDB server is running.Ezra Siton
dab edit ... instead of change arg name you've made OrderInput unusable/unecessary .... use "normal" resolver args name if you don't know what's going on ... optimize laterxadm
I've done just that and the Error I'm getting now is 'TypeError: Cannot read property 'create' of undefined'alademerin

1 Answers

0
votes

So here's how I fixed the problem.

in the index.js file

import cors from 'cors';
import express from 'express';
import jwt from 'jsonwebtoken';
import mongoose from 'mongoose';
import { ApolloServer, AuthenticationError } from 'apollo-server-express';

import schemas from './schemas';
import resolvers from './resolvers';

import userModel from './models/userModel';
import orderModel from './models/orderModel';
import shawarmaModel from './models/shawarmaModel';

const app = express();
app.use(cors());

const getUser = async (req) => {
  const token = req.headers['token'];

  // console.log(token)

  if (token) {
    try {
      return await jwt.verify(token, 'riddlemethis');
    } catch (e) {
        console.log(e)
      throw new AuthenticationError('Your session expired. Sign in again.');
    }
  }
};

const server = new ApolloServer({
  typeDefs: schemas,
  resolvers,
  context: async ({ req }) => {
    if (req) {
      const me = await getUser(req);

      return {
        me,
        models: {
          userModel,
          orderModel, //this was where the orderModel was misspelled as OrderModel
          shawarmaModel
        },
      };
    }
  },
});

server.applyMiddleware({ app, path: '/graphql' });

app.listen(5000, async () => {

    await mongoose.connect('mongodbconnectionString')
});

in the code above, I have commented the section in which the error was from. Carelessly, when debugging I overlooked checking this file. my mistake. I apologise for not including this code in the original question