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
just change the route name for example
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.
Insted change its order to