I'm trying to retrieve all the keys off a query result into an array. Should be a super easy thing to do but somehow am not able to. Here's the snippet:
fromMongoDB = parent.posts[0]
returnedkeys = Object.keys(fromMongoDB);
console.log(fromMongoDB);
console.log('-----------------------------');
console.log(returnedkeys);
The data I'm receiving into fromMongoDB
is an object with two key-value pairs:
{
id: <some ID>,
title: <some title>
}
Using Object.keys()
, I intend to get an array of the two keys:
[
id, title
]
But this is what I'm getting instead:
{ id: '5ba1f3e7cc546723422e62a4', title: 'A Title!' }
-----------------------------
[ '__parentArray',
'__parent',
'__index',
'$__',
'isNew',
'errors',
'_doc',
'$init' ]
What am I doing wrong? Is fromMongoDB
not a JSON object?
You can try below aggregation in mongodb 3.4.4 and above
db.collection.aggregate([
{ "$project": {
"keys": {
"$objectToArray": "$$ROOT"
}
}},
{ "$project": { "keys": "$keys.k" }}
])
尝试这样的事情:
Object.getOwnPropertyNames(fromMongoDB);
Try lean() function instead. Append .lean() to your query and then use Object.keys() to get an array of keys.
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.