Schema:
{
img: // array of minimum length 1 of ObjectIds or field is "missing" to indicate that array is empty
tar: [
{ img: // array of minimum length 1 of ObjectIds or field is "missing" to indicate that array is empty },
{ img: // array of minimum length 1 of ObjectIds or field is "missing" to indicate that array is empty },
...
]
}
This is my query to delete a photo, which is an ObjectId in the top level img
array, and may be in the img
field of some tar
subdocuments:
await mongo_tran_ses.withTransaction(async () => {
// pulling the ObjectId matching `req.params._id` from `img`, and all `tar.img`
await user.updateOne(
{ _id: ObjectId(req.user._id) },
{
$pull: {
img: { _id: { $eq: ObjectId(req.params._id) } },
"tar.$[].img": { $eq: ObjectId(req.params._id) },
},
},
{ session: mongo_tran_ses }
);
// removing all `tar.img` if it is now an empty array
await user.updateOne(
{
_id: ObjectId(req.user._id),
},
{
$unset: {
"tar.$[element].img": "",
},
},
{
arrayFilters: [{ "element.img": { $size: 0 } }],
session: mongo_tran_ses,
}
);
// removing `img` if it is now an empty array
await user.updateOne(
{
_id: ObjectId(req.user._id),
img: { $size: 0 },
},
{
$unset: {
img: undefined,
},
},
{
session: mongo_tran_ses,
}
);
}, tran_option);
The goal:
Perform the above with just one update
query instead of the 3 above.