猫鼬:仅返回文档中的键 [英] mongoose: return only keys from a document
问题描述
我的文档如下:
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屋!