0

I am trying to fetch Distinct data from MongoDb using NodeJs.I am getting data in JSONArray form as I am not getting key from MongoDb.

Below is my code:

const coll = client.db("mydb").collection("ItemsAddedByAdmin");
coll.distinct("product_name",(function(err,docs){                     
   res.send({"product_name":docs});
}));

Below is my OUTPUT

{
"product_name": [
    "Biology",
    "Chemistry",
    "Crown",
    "Crown Junior",
    "Long Book",
    "Long Book A4",
    "Physics",
    "Sketch Book",
    "Universal"
  ]
}

and when I am trying below code I am getting no values.

const coll = client.db("mydb").collection("ItemsAddedByAdmin");
coll.distinct("product_name",(function(err,docs){
   let output = docs.map(r => ({'product_name':docs.product_name}));
   res.send(output);                        
}));

OUTPUT

[
{},
{},
{},
{},
{},
{},
{},
{},
{}
]

I want values in key value pair like given below:

[
 {
   "product_name":Book
 },
 {
   "product_name":Pencil
 }  
]

Someone please let me know how can I get desired result any help would be appreciated.

THANKS

3 Answers 3

1

Just a small change and it should start working:

const coll = client.db("mydb").collection("ItemsAddedByAdmin");
coll.distinct("product_name",(function(err,docs){

      let output = docs.map(r => ({'product_name':r})); // r contains the item of array at respective index
      res.send(output);       

}));
Sign up to request clarification or add additional context in comments.

Comments

1

Need to use only r in your map function

 let output = docs.map( r => ({'product_name': r})); 

Comments

0
db.getCollection('coll').find({},{product_name:1,_id:0})

1 Comment

This will return same values available in database and not distinct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.