How to get specific distinct field from mongoose?

Viewed 22

I have db collection like this

[
{
name: "Fried Burger",
image: "https://burgerimage.com",
category: "burger"
},
{
name: "Fried Pizza",
image: "https://pizzaimage.com",
category: "pizza"
},
{
name: "Veg Pizza",
image: "https://vegpizzaimage.com",
category: "pizza"
},
{
name: "Fried Pasta",
image: "https://friedpastaimage.com",
category: "pasta"
}
]

Is there any way I get value from category without repeating and single image although there are multiple categories like this

[
{category: "burger", image:"https://burgerimage.com"},
{category: "pizza", image:"https://pizzaimage.com"}, //Any image works as long as category is same
{category: "pasta", image:"https://pastaimage.com"}

I used .distinct('category') but it only returns like this but I also want one image with that

{
  "category": [
    "Burger",
    "beef",
    "chicken",
    "duck",
    "pasta",
    "pizza",
    "pork"
  ]
}
1 Answers

If you want just category and image of each one try this


MyModel.find({} , 'category image', function(err, docs) { })
Related