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?
.models\Post.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
controllers\posts.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}`);
actions\posts.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);
}
};