I have an API call in which i want merge two objects and return them
router.get('/reviewsavg', async (req, res) => {
try {
//enitityId[] is an array consisting of ID's to look up form
const promise = [];
Object.keys(entityId).forEach(async (key) => {
const reviews = Review.aggregate([
{ $match: { entityId: ObjectId(entityId[key]) } },
{
$group: {
avg: { $avg: '$rating' },
},
},
]);
const entit = Entity.find({ _id: entityId[key] });
promise.push(entit, reviews);
});
const results = await Promise.all(promise);
res.send(results);
} catch (e) {
res.status(500).send();
}
});
in this reviews
look like
[
[
{
"_id": null,
"avg": 5
}
],
[
{
"_id": null,
"avg": 3.66666
}
]
]
and entit
looks like this
[
[
{
"public": false,
"name": "second",
"createdAt": "2020-05-09T16:28:38.493Z",
"updatedAt": "2020-05-09T16:28:38.493Z",
"__v": 0
}
],
[
{
"public": false,
"name": "first",
"createdAt": "2020-06-09T16:28:38.493Z",
"updatedAt": "2020-06-09T16:28:38.493Z",
"__v": 0
}
]
]
I want to merge these two send them back, I want the response like this
[
{
"public": false,
"name": "first",
"createdAt": "2020-06-09T16:28:38.493Z",
"updatedAt": "2020-06-09T16:28:38.493Z",
"__v": 0,
"_id": null,
"avg": 3.66666
}
]
Till now I have tried
1.
const merged = [...entit, ...reviews];
promise.push(merged);
returns []
2.
const merged =entit.concat(reviews);
promise.push(merged);
returns error that entit.concat
is not a function.
3.
Tried Object.assign()
that too doesn't work
What else can I do here?