Reputation: 50
I am destructuring the value of an object from an array. If array is empty, error happens. How to make default value, if array is empty?
Error happens if array, which I am destructuring is empty:
"TypeError","message":"Cannot destructure property
payments
of 'undefined' or 'null'."
Code of destructuring (await (...).toArray()
is returning array [ { payments: @integer } ]
):
({
[0]: { payments: users.finances.payments = 0 },
} = await (
await payments_collection.aggregate([
{
$group: {
_id: null,
payments: { $sum: '$coins' },
},
},
])
).toArray());
Upvotes: 0
Views: 61
Reputation: 50
@adiga, thanks for your answer.
I replaced { [0]: { payments: users.finances.payments = 0 } }
with [{ payments: users.finances.payments = 0 } = {}]
New working code:
[{ payments: users.finances.payments = 0 } = {}] = await (
await payments_collection.aggregate([
{
$group: {
_id: null,
payments: { $sum: '$coins' },
},
},
])
).toArray();
Upvotes: 0