Home > OS >  how do fetch post from database based on user selected category
how do fetch post from database based on user selected category

Time:12-30

this is my get api request

// fetch video based on category

router.get("/category/:id" , async(req , res) => {

    try {

        const allpost = await Post.find();
        const user = await User.findById(req.params.id)
         
        const postCategory = await Promise.all(
            user.category.map((item) => {
                return [item];
            })
        )
        // const postCategory = "Entertainment"

        let postCategorydetail = allpost.filter((val) => {
            return postCategory.map((item) => {
                return item.user == val.category
            })
        })

        let filterpost = await Promise.all(
            postCategorydetail.map((item)=>{
                const {...others} = item._doc;
                return others
            })
        )

        res.status(200).json( postCategorydetail);

    } catch (error) {
        return res.status(500).json("internal server eroor")
    }

});

these categories were selected by users

these info stored in a user database and when they try to upload new post they select any of these category.

i wanna fetch post particularly based on user catagory

[
  {
    "user": "Entertainment"
  },
  {
    "user": "Combat Training"
  },
  {
    "user": "Album songs"
  },
  {
    "user": "Lifestyle"
  },
  {
    "user": "Sports"
  },
  {
    "user": "History"
  }
]

i am trying to fetch post from database based on user previously selected category

CodePudding user response:

I'm not pretty sure about what are you looking for, but maybe is this:

Inside you try part of the try-catch block:

const user = await User.findById(req.params.id)

const postCategories = user.postCategories // I suppose this is an array

// this returns all posts in which category is in user categories
const postCategoriesDetails = await Post.find(
    { category: { $in: postCategories } }
)

const filterPost = postCategoriesDetails.map(postCategoryDetails => {
    const { ...others } = postCategoriesDetails._doc
    return others
})

res.status(200).json(postCategoriesDetails);
  • Related