猫鼬:仅返回文档中的键 [英] mongoose: return only keys from a document

查看:96
本文介绍了猫鼬:仅返回文档中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档如下:

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]

所以我有以下代码:

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

无论如何,我可以摆脱文档中没有的这些键吗? 我知道这里的mapreduce答案 MongoDB获取所有名称MongoDB集合中的键,但我不知道如何将其转换为猫鼬. AFAIK猫鼬不支持runCommand.

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.

推荐答案

您必须使用_doc属性,因为它包含您的实际文档.此外,您可以只使用 Object.keys 获取属性列表.

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

这篇关于猫鼬:仅返回文档中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆