academind / yt-graphql-react-event-booking-api

Code for GraphQL + React Event Booking API Series: https://academind.com/learn/node-js/graphql-with-node-react-full-app/
394 stars 302 forks source link

Getting the _doc undefined error. #6

Open shellybranch2018 opened 5 years ago

shellybranch2018 commented 5 years ago

I'm following along in the course, building the app and tried running the first query in #7, Dynamic Relations.

query { events { creator { email } } } Result from terminal UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property '_doc' of undefined.

shellybranch2018 commented 5 years ago

Here is my code: rootValue: {

    events: () => {
        Event.find().populate('creator')
        .then(events => {
              return events.map(event =>{
                return { ...event._doc,
                     _id: event.id,
                    creator: {...event._doc.creator._doc,
                    _id: event._id

                    }
                };

            });
        }).catch(err => {
            throw err;
        });
    },
    createEvent: (args) => {
    const event = new Event({
        title: args.eventInput.title,
        description: args.eventInput.description,
        price: +args.eventInput.price,
        date: new Date(args.eventInput.date),
        creator: '5c7ec597d0578c1420b3894c'

    });
    let createdEvent;
     return event
     .save()
     .then(result => {
         createdEvent = {...result._doc, _id: result._doc._id.toString()};
       return User.findById('5c7ec597d0578c1420b3894c')

     })
     .then(user => {
        if(!user) {
            throw new Error('User not found.');
        }
        user.createdEvents.push(event);
        return user.save();
     })
    //  .then(result =>{
    //     return createdEvent;
    //  })
     .catch(err => {
         console.log(err)
         throw err;
     });

    },
    createUser: (args) => {
        return User.findOne({
            email: args.userInput.email
        }).then(user => {
            if(user) {
                throw new Error('User exist already.')
            }
            return bcrypt.hash(args.userInput.password, 12)
        })
        .then(hashedPassword => {
            const user = new User({
                email: args.userInput.email,
                password: hashedPassword
            });

            return user.save();
        })
        .then(result => {

            return {...result._doc, password: null, _id: result.id };
        })

        .catch(err => {
            throw err;
        })

    }
},
graphiql: true

})

);