0

For each post I have this structure:

{
  "_id": "5dfd3b918937d40b98afd3f8",
  "user": "5deea38cfc84f42590e01942",
  "title": "test",
  "description": "description test",
  "category":
    {
      "0": "1",
      "1": "101"
    },
  "phone": "+1",
  "country": "USA",
  "city": "NY",
  "options": {
    "transaction_type": ""
  },
  "date": "2019-12-20T21:22:25.940Z",
}

In express I using bottom code for find posts by category id but not working what I should to do?

router.get("/category/:category", async (req, res) => {
  try {
    const posts = await Post.find({
      category: { $all: req.params.category }
    }).sort({ date: -1 });
    if (!posts) {
      return res.status(404).json({ msg: "Ads not found" });
    }
    const resultPosts = posts.slice(req.query.start, req.query.count);
    res.json(resultPosts);
  } catch (err) {
    console.error(err.message);
    if (err.kind === "ObjectId") {
      return res.status(404).json({ msg: "Ads not found" });
    }
    res.status(500).send("Server Error!");
  }
});
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
MaK
  • 121
  • 1
  • 8
  • Can you be more specific about what isn't working? – Drew Reese Apr 22 '20 at 06:08
  • Are you using MongoDB. If yes, there is an method called findById. You can use this method. – Jeyanth Kanagaraj Apr 22 '20 at 06:12
  • @DrewReese for example I want to get all posts that have category 1, Please see my other question [link](https://stackoverflow.com/questions/61352430/what-structure-for-create-tree-category-and-set-in-posts-is-better-and-find-pos) – MaK Apr 22 '20 at 07:46
  • @JeyanthKanagaraj Yes I using MongoDB but for example I want to get all posts that have category 1 , Please see my other question [link](https://stackoverflow.com/questions/61352430/what-structure-for-create-tree-category-and-set-in-posts-is-better-and-find-pos) – MaK Apr 22 '20 at 07:47
  • @DrewReese I have problem in this line `Post.find({ category: { $all: req.params.category } })}` – MaK Apr 22 '20 at 07:48
  • @DrewReese , Check the following link. This will help you. https://blog.jscrambler.com/build-database-relationships-with-node-js-and-mongodb/ – Jeyanth Kanagaraj Apr 22 '20 at 07:50

0 Answers0