Skip to content

Instantly share code, notes, and snippets.

@iMohamedSamir
Last active April 9, 2022 02:03
Show Gist options
  • Save iMohamedSamir/1ec62f10503138a332907582cf39444d to your computer and use it in GitHub Desktop.
Save iMohamedSamir/1ec62f10503138a332907582cf39444d to your computer and use it in GitHub Desktop.
Solving: Cast to ObjectId failed for value "" at path "_id". following freeCodeCamp.org's tutorial: React / GraphQL Course - Build a social media app (MERNG Stack) at 1:18:00
/*
* When following freeCodeCamp.org's youtube video tutorial: React / GraphQL Course - Build a social media app (MERNG Stack)
* I have got stuck @1:18:00 because I got a weired error: Cast to ObjectId failed for value "" at path "_id".
* It turn out that that ModelName.findById() method only expect vaild mongodb ID, so all I did is
* to use Types.ObjectId.isValid from mongoose to check if the given string is vaild id or not, if not,
* Skipped making the query and I threw new "Post not found" Error.
*/
import mongoose from 'mongoose';
import { Post } from '../../Models/Post.js'
export const postResolvers = {
Query: {
getPosts: async () => {
try {
const posts = await Post.find();
return posts;
} catch (err) {
throw new Error(err);
}
},
getPost: async (_, { postId }) => {
// validate if postId before is vaild ID before using it.
const isValidId = mongoose.Types.ObjectId.isValid(postId)
// if vaild
if (isValidId) {
try {
const post = await Post.findById(postId);
if(post) return post;
} catch (err) {
throw new Error(err);
}
} else {
// if not valid, I'm skipping the query and I throwing new error with Post not found string.
throw new Error('Post not found');
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment