qts
qts

Reputation: 1044

mongoose: return only keys from a document

I have a document as follows:

var data={"john:"friend",
          "fruit":"banana",
           "tv":[{"livingroom":"led",
                   "bedroom":"lcd"
                   "fruit":"banana"}]}

and I am trying to return an array of all its unique keys as follows:

["john","fruit,livingroom,bedroom]

so I have the following code:

var mykeys=[];
database.find({},function(result){
    result.forEach(function(each){
         for (key in each){
             mykeys.push(key)
         };
    }});

But this returns a whole bunch of objects I don't need like:

[$__, isNew, errors, _doc, $__original_save, save, _pres, _posts....]

Is there anyway I can get rid of these keys which aren't in the document? I am aware of this mapreduce answer here MongoDB get the names of all the keys in a MongoDB collection but I do not know how to translate it into mongoose. AFAIK mongoose doesn't support runCommand.

Upvotes: 1

Views: 8446

Answers (3)

Ilya Izrailyan
Ilya Izrailyan

Reputation: 1

Adding to @str answer, don't forget to add error as first callback argument

  let tableKeys 
  TRow.findOne({}, (err, result) {
    tableKeys = Object.keys(result._doc);
  });

You might also want to delete '_id' and '__v' from your keys object

Upvotes: 0

Piotr S.
Piotr S.

Reputation: 21

Not sure if you may still need it, but i manged to get it done in Nestjs and Mongoose using this code:

    async leadModel(): Promise<any> {
    const keys = this.leadsModel.findOne();
    return Object.keys(keys.schema.obj)
}

It's still not the best version of it and also throws me a warning that the property doesnt exist on my type, but it works perfectly. Returns only keys of the collection. If you remove Object.keys() it will also return nested keys.

Upvotes: 1

str
str

Reputation: 44979

You have to use the _doc property as this contains your actual document. In addition, you can just use Object.keys to get a list of properties.

var mykeys;
database.findOne({}, function(result) {
    mykeys = Object.keys(result._doc);
});

Upvotes: 8

Related Questions