I have an document structure like this:
_id: 123,
posts: [
{
_id: 234,
likesUser: [345, 456, 567, 678]
}
]
I want to use $reduce here so my expected output should look like this:
output: {
likes: [23, 31, 12, 32], //each element is the size of the "likesUser" array
ids: ["14312", "2342", "2312", "235234"] //each element is the "_id" in the posts array
}
I have try it like this:
let result = await Post.aggregate([
{
$match: {
_id: USER
}
},
{
$project: {
posts: {
$reduce: {
input: "$posts",
initialValue: { likes: [], ids: [] },
in: {
likes: {
$push: { $size: "$$this.likesUser" }
},
ids: {
$push: "$$this._id"
}
}
}
}
}
}
]);
In my frontend i use chart.js. The yAxsis are the likes and the xAxsis are the ID's. So for every element in my posts array i need the length of likesUser and _id
But it doenst work. Has anybody an idea how to achive this?