Mitigating MongoDB injection attacks with Mongoose Mitigating MongoDB injection attacks with Mongoose mongodb mongodb

Mitigating MongoDB injection attacks with Mongoose


While you could use $eq to ensure an equality comparison is used in the query, your express route handler is a better place to perform request format validation.

A valid POST /login should have userName and password string fields in the body of the request. If not, it should be rejected before it even gets to Mongoose.


Additionally, you can use npm package "mongo-sanitize" as given as per their documentation as below:

var sanitize = require('mongo-sanitize');// The sanitize function will strip out any keys that start with '$' in the input,// so you can pass it to MongoDB without worrying about malicious users overwriting// query selectors.var clean = sanitize(req.params.username);Users.findOne({ name: clean }, function(err, doc) {  // ...});

If sanitize() is passed an object, it will mutate the original object.