I wanna perform some actions upon inserting a document. The details are like this:
I have 2 collections called “product” and “import”. The product collection has the field “availability” indicating how many products are there in total. The import collection has the field “amount” indicating how many products are being imported.
When inserting an import document, I would like to increase the field “availability” by the “amount”. So I created a trigger and I was able to achieve what I want. So far so good.
But the problem is there is a constraint for the import collection. The “amount” field must be a positive number. So I would like to reject the document if it doesn’t satisfy the condition. But I can’t seem to find the way. Because when the trigger is triggered, the document was already inserted to the collection. What am I supposed to do? Should I delete the document by its _id? That doesn’t seem like a right way to do it. I am thinking of something like “trigger before” like in any RDBMS. Should I perform the validation on client machines? If so, what if somebody inserts documents directly by using the console on the web?
I am totally new to mongodb as well as any NoSQL in general. So maybe my mindset of designing database is inappropriate. I will appreciate anyone’s help.