简体   繁体   中英

How to get all keys + in a collection + mongodb +mongoose

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..

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM