How I use MongoDB triggers

In this post I will show the function I use in my MongoDB trigger. I … Read more How I use MongoDB triggers

In this post I will show the function I use in my MongoDB trigger. I use MongoDB in many of my personal projects, and since they are mostly for test and portfolio purposes, I need a way to reset the DB daily by leaving only the data I want. MongoDB triggers are excellent for that, and you can set them up easily on your MongoDB account by following this guide, which I won’t repeat here.

Here I want to show the function I use in the trigger, because it took me a while to figure out a working solution, so I hope I can help others that may encounter the same problems I had.

https://medium.com/media/20c5635d7efd74d0e1193fa036f97f39/href

The code above is the function for a scheduled trigger. The function first finds the user I want to keep in the DB, called testuser (line 4), then utilizes the user _id to remove the blogs that do not belong to testuser (line 13). Notice on line 13 the use of $ne, which stands for “not equal”. The same logic is repeated to remove the unwanted comments (line 28). After that, to remove the unwanted comment references from the blog documents (stored in blog.comments array), I first get all the left blog documents (line 24) and all the left comment documents (line 25), then I save the returned FindCursors as arrays (lines 26 a& 27), filer only the comments references of existing comments from the blog document (line 30), and finally update the blog document (line 31–35).


How I use MongoDB triggers was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


Source: Level Up Coding


Categories: NewsTags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *