Search code examples
mongoosemongoose-schema

CastError: Cast to ObjectId failed for value "search" (type string) at path "_id" for model "PostMessage"


Getting cast error while performing query search in mongoose


export const getPostsBySearch = async (req, res) => {
    const {searchQuery, tags} = req.query
    try {
        const title = new RegExp(searchQuery, 'i')
        const posts = await PostMessage.find({ $or: [{ title: String(title) }, {tags: {$in: tags.split(',')}}] })
        res.json({data: posts})
    } catch (error) {
        console.log(error)
        res.status(404).json({message: error.message})
    }
}

invoking it

getPostBySearch({search: 'none', tags: 'wonders'})

i am expecting a array of post with associated filters


Solution

  • It may be the problem of how you arrange your routes in your server-side code.

    You may refer to here.

    In my case I simply rearrange the routers from

    router.get("/", getPosts);
    router.get("/:id", auth, getPost);
    router.get("/search", getPostsBySearch);
    

    to

    router.get("/search", getPostsBySearch);
    router.get("/", getPosts);
    router.get("/:id", auth, getPost); # routes with id need to come after other routes
    

    Hope this can help!