Reputation: 259
I have the following code. Image is an array and I want everything outputted except Path that exists within image. How can it be achieved ? image contains - ID, Title, Path
if (dbRes !== null) {
res.apiSuccess({
town: dbRes.town,
county: dbRes.county,
postCode: dbRes.postCode,
image: dbRes.image
});
} else {
res.apiError(messages.product.not_found);
}
Here is screenshot of output:
Upvotes: 0
Views: 114
Reputation: 3106
UPDATE: OP shared the object which showed the definition of each parameter which changes the response traversal.
You can convert your dbres to object using mongoose build in function. And then just use delete command to delete the attribute from image before you pass it in the response.
Per the response above we are assuming that dbRes is an array of objects containing attributes image, town, county, and postCode. And image is also an array of objects.
if (!dbRes) {
// Convert db res to object and destructure attributes
const dataArr = dbRes.toObject(); // Array of objects
const response = dataArr.map((data) => {
const {
town,
county,
postCode,
image = [] // Add default so that we don't have to check for null/undefined
} = data;
const newImageArr = image.map((imageData) => {
// Delete path attribute from image object
delete imageData.path;
return imageData;
});
return {
town,
county,
postCode,
image: newImageArr,
}
});
res.apiSuccess(response);
} else {
res.apiError(messages.product.not_found);
}
Resources:
DB Level Omit
All these being said, if you don't need to use the path variable at all before you send the response then just omit it at the db level. This way you don't need to traverse object. Checkout the selection functionality of mongoose in this post https://stackoverflow.com/a/24348603/14167216
Upvotes: 1
Reputation: 1822
You can use dot notation
and mongodb projections
to exclude the path
field from the array of images
.
db.collection.findOne({
_id: dataId
}, {
"image.path": 0
})
The following query assumes that the document has an _id
field and has a array of images
at the first level. This query will return the entire document, only excluding the path
fields in images
array
Upvotes: 1