0

I want to get all distinct keys from a collections in mongoDB. I refereed the following links:

Get names of all keys in the collection

Querying for a list of all distinct fields in MongoDB collection and etc.

But still i didn't get the right solution...

As i am using mongoose in the first link reference syas runCommand is not a function.

As findOne() will give the first document keys alone but i need all distnct keys

userModel.findOne(condition, projection, callback) 

Please share your ideas..

Subburaj
  • 5,114
  • 10
  • 44
  • 87

2 Answers2

0

If you are using Mongoose 3.x, then you can try this :

userModel.find().distinct('_id', function(error, ids) {
    // ids is an array of all ObjectIds
});

Or you can find all the documents and extract key from that like :

var keys = {};
var docKeys = [];
userModel.find({}, function(err, allDocs){
    allDocs.forEach(function(doc){
        docKeys = Object.keys(doc);
        docKeys.forEach(function(docKey){
               if(!keys[docKey]) keys[docKey] = true;
        })
    })     
})

I have just written for getting logic, you can change according to your requirements and efficiency

Tushar Nikam
  • 594
  • 4
  • 13
0

Try like this you will get all of your keys defined into your mongoose model/Schema.

import Model from 'your_model_path'

for(let property in Model.schema.obj){
  console.log("key=====>",property);
}
Osman Goni Nahid
  • 1,193
  • 2
  • 15
  • 24