skip to Main Content

everyone!
I am relatively newbie to web dev and have been watching mern project tutorial on Youtube. I am trying to implement searching functionality for posts. Posts are stored in MongoDB. After inserting title and/or tags for search form keep getting this error. {"message":"Cast to ObjectId failed for value "search" (type string) at path "_id" for model "Post""}. I am thinking that mongoose mistaking my search req.query for _id req.param but i am not sure. Any suggestions how to solve this error?

.modelsPost.js

import mongoose from 'mongoose'

const PostSchema = new mongoose.Schema(
    {
        title: String,
        message: String,
        name: String,
        creator: String, 
        tags: [String],
        selectedFile: String,
        likes: {
            type: [String],
            default: [],
        },
        createdAt: {
            type: Date,
            default: new Date()
        }
    }
)

const Post = mongoose.model('Post', PostSchema)

export default Post

controllersposts.js

export const getPostsBySearch = async (req, res) => {
    const { searchQuery, tags } = req.query;

    try {
        const title = new RegExp(searchQuery, "i");

        const posts = await Post.find({ $or: [ { title }, { tags: { $in: tags.split(',') } } ]}).exec();

        res.json({ data: posts });
    } catch (error) {    
        res.status(404).json({ message: error.message });
    }
}

axios endpoint

export const fetchPostsBySearch = (searchQuery) => API.get(`/posts/search?searchQuery=${searchQuery.search || 'none'}&tags=${searchQuery.tags}`);

actionsposts.js

export const getPostsBySearch = (searchQuery) => async (dispatch) => {
  try {
    dispatch({ type: START_LOADING });
    const { data: { data } } = await api.fetchPostsBySearch(searchQuery);

    dispatch({ type: FETCH_BY_SEARCH, payload: { data } });
    dispatch({ type: END_LOADING });
  } catch (error) {
    console.log(error);
  }
};

2

Answers


  1. just change the route name for example

    router.get("/v1/search", getPostsBySearch);
    
    export const fetchPostsBySearch = (searchQuery) => API.get(`/posts/v1/search?searchQuery=${searchQuery.search || 'none'}&tags=${searchQuery.tags}`);
    
    Login or Signup to reply.
  2. In your router place the /posts/search router above /posts/:id. The query is going to the route /posts/:id and is trying to cast the string value "search" to object id.

    In this case the search query is being addressed by getPost instead of getPostBySearch.

    postRouter.get('/:id', getPost);
    postRouter.get('/search', getPostsBySearch)
    

    Insted change its order to

    postRouter.get('/search', getPostsBySearch)
    postRouter.get('/:id', getPost);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search