Sanitize user input in Mongoose Sanitize user input in Mongoose mongodb mongodb

Sanitize user input in Mongoose


It seems like the mongo-sanitize npm module is the place to start for the raw escaping functionality. Honestly this sounds more appropriate at the connect/express middleware layer because at the mongoose layer, by design, the code does not exert any expectations on the query/update parameters in terms of whether they are written by the application developer (in which case they must not be sanitized or they won't function correctly) or involve user input (which must be sanitized). Thus I'd recommend middleware functions to sanitize the most common places for user input to enter: req.body, req.query, and req.params. So for example you might do something like (sketch):

var json = require("body-parser").json;var sanitize = require("mongo-sanitize");function cleanBody(req, res, next) {  req.body = sanitize(req.body);  next();}function updateUser(req, res) {  //...  // safe to build an update query involving req.body here}app.put("/api/users", json(), cleanBody, updateUser);


There is a new tool providing auto control of coming URL and html body data. https://www.npmjs.com/package/content-filter

Also native escape() method might be used for to protect the database.

Run the code snippet below to see the results.

let a = "{$gt:25}"console.log(a)console.log(escape(a))