Reputation: 459
I need to convert a mongo document in Angular, into an array of key value pairs like shown below. e.g. when a client document is recd, the whole document needs to be converted into an array as shown below.
There is an aggregation option in MongoDb - $objectToArray
{ $objectToArray: { item: "foo", qty: 25 } }
result:
[
{
"k" : "item",
"v" : "foo"
},
{
"k" : "qty",
"v" : 25
}
]
I could not find this in Mongoose documentation? Is it available?
Is there a way to achieve this in Angular when the document is received from Node API?
Upvotes: 0
Views: 1506
Reputation: 756
Yes, you can use $objectToArray
in the aggregation pipeline and it will also work in mongoose, you try a query like this
Model.
aggregate([{
$project: { sampleField: { $objectToArray: "$array" } }
}]).exec();
In case, if you want to convert the whole document into an array you can try this pipeline
db.collection.aggregate([
{
"$match": {
_id: 1
}
},
{
// Add this stage in
//case you want to exclude some keys
"$project": {
_id: 0
}
},
{
$project: {
data: {
$objectToArray: "$$ROOT"
}
}
}
])
Here is a link to test the query in the playground: Mongo Playground
OR
If you want to do it in Angular then you can try this code
let object = { item: "foo", qty: 25 }
let result = Object.entries(object)
.map(itr => {
return {k: itr[0], v: itr[1]}
})
console.log(result)
Upvotes: 1