What is the right way to do what I did in the next code?
I use here lots of requests to the DB, how can I do this with less?
const publishFilter: { [key: string]: any } = {
date: timeUtil.dateAsLocal,
"products.product_source_id": params.productId,
};
const publishDoc = await Publish.findOneAndUpdate(publishFilter, {
$set: { "products.$": nextPublishPayload },
});
if (!publishDoc) {
const existsDoc = await Publish.exists({ date: timeUtil.dateAsLocal });
if (!existsDoc) {
const nextDoc = new Publish({
date: timeUtil.dateAsLocal,
products: [nextPublishPayload],
});
await nextDoc.save();
} else {
await Publish.findOneAndUpdate(
{ date: timeUtil.dateAsLocal },
{
$push: { products: nextPublishPayload },
},
);
}
}