Do we need to strain or filter user queries in Mongoose for security purposes?

As a long time web dev, my usual answer to everything is use RegEx checking to strain user input. When I'm looking at Mongoose queries, my gut is telling me I don't necessarily have to strain the input, assuming a length check maybe.

This is assuming the express framework has already filtered down the input to either req.body or req.query.

For example, a typical query could be like so in Mongoose:

User.findOne({ username : req.query.username }, function(err, doc) {
  // code
});

Is it possible to inject bad things into this specific query? I would expect yes as it seems hackers always employ very clever things, but would like to see some examples of this. I ask this because this is different than other ways of doing this in terms of not doing string concatination, rather using an object that is already a string or undefined. Thanks!

Please move this if its off topic and I apologize in advance as I was not sure where to ask this.

It's safe when req.query.username is a value that you expect (like a string). It won't try to evaluate any JSON inside of it. In case req.query.username is an Object like e.g. { '$exists': true } it will be evaluated and return unexpected documents.

Your findOne example is fairly 'safe' because you would err on validating the password. With other queries like .remove() it's much more dangerous.

var param = { '$exists': true };

User.remove({ username : param }, function (err, affected) {
    console.log(err)
    console.log(affected)
});

This would delete all the users in the collection:

Does that help?


Edit:

There are similar issues when working with PHP and Mongo. Much of it would depends on the express framework not creating objects from input parameters.