I'm trying to return icons, as a result, to produce them on the page
The following code below map
all the results that I'm trying to return to the page.
const icons = await Icon.find({ _id: { $in: ids } }).select({ ...options.select, ...options.additional })
const results = ids
.map(id => {
const iconsGroup = icons.find(icon => icon.id === id)
if (query.hasPublishingError) {
iconsGroup.icons = iconsGroup.icons.filter(el => (el.errorsData.length > 0 && el.status === 'draft'))
}
return iconsGroup
})
.map(i => i.toJsonWith(options.select))
await postProcess(results)
return {
docs: results,
limit: response.limit,
page: response.page,
pages: response.pages,
total: response.total
}
When I'm making a GET
request, I'm getting an error such as:
TypeError: Cannot read property 'toJsonWith' of undefined\n
The painful point is .map(i => i.toJsonWith(options.select))
By the way, for some reason, this function toJsonWith
cannot be found as a declaration somewhere.
Please help me, I'm trying to figure out what's wrong here for 4 days.
CodePudding user response:
an _id should always be unique so
const iconsGroup = icons.find(icon => icon.id === id)
should return an arrayObject with a maximum of one Element.
Then you check for publishing errors
if (query.hasPublishingError) {
iconsGroup.icons = iconsGroup.icons.filter(el => (el.errorsData.length > 0 && el.status === 'draft'))
}
And here it can happen that iconsGroup is an empty array.
Next you make a second map to use your magical toJsonWith (i also don't know what it does).
You can combine these two maps and iterate direclty over your icons instead of using a map on your ids (following code gives you an array of icons depending of query.hasPublishingError):
const results = icons.map(icon => {
if (query.hasPublishingError && icon.errorsData.length > 0 && icon.status === 'draft') {
return icon.toJsonWith(options.select)
} else {
return icon.toJsonWith(options.select)
}
})