Trigger - Can I reject the document being inserted?

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.

Hi @Dao_Lac - welcome to the community forum!

You’re correct that it’s too late to prevent the write once the trigger has been invoked.

You have a couple of options:

  1. Have the trigger undo the write (downside is that the application will see that the original write passed, and it won’t get a notification that the write was undone)
  2. Implement a Realm function for the app to call to change the original document – it can then make the checks, update that document, and process any side effects.

Hey Dao!

In addition to what Andrew mentioned, you may also want to try out the change validation that’s built in to Realm’s JSON schemas. You can validate that amount is always greater than zero and, if it isn’t, reject the insert/update.

  "title": "Import",
  "properties": {
      "amount": { "bsonType": "int" }
  "validate": {
      "amount": { "$gte": 0 }

Using the above schema you could test that it works with the following function:

exports = async function(arg){
  const importCollection ="mongodb-atlas").db("test").collection("import")
  await importCollection.insertOne({ amount: 3 }); // This will succeed because amount >= -1
  await importCollection.insertOne({ amount: -1 }); // This will fail with a schema validation error