How to best sanitize queries?

Hello, let me preface saying that I am new to mongoDB and Motor.
As with any database, it is importante to sanitize queries to prevent malicious users from injecting bad queries into your system. What is the best way to do this with Python and Motor? I am using FastAPI.
I found a few references to a node package for sanitizing mongoDB queries, but the only resource I found for Python is a fairly unknown plugin https://github.com/noamt/python-mongo-sanitizer

Reference:

Hi! Thank you for your question. So as opposed to SQL databases, MongoDB is strongly typed. So in python the best way to validate a field is to simply cast it to the type that you expect. This works very well for ints and strings, however if you need to validate a field that accepts a dictionary, then you also need to check and make sure that you are passing the correct operator. What that library does is simply removes any operators from a dictionary, which also works. However, the simplest and easiest way is by attempting to coerce the value to it’s expected type: age = int(age)

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.