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());
@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();
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.