ragulka
ragulka

Reputation: 4342

How to sanitize user input in mongoose?

I am trying to sanitize user input in mongoose. I though that using mongoose middleware would help, but it seems that I am either wrong or I am doing something wrong.

The reason I am trying to use Mongoose middleware (and not Express middleware) is that I have a document that can have a nested document - however, that nested document can be a standalone document as well. I am trying to create a "single point of truth" for my documents so that I can sanitize only in one place.

The following code does not seem to work:

Organization.pre("validate", function (next) {
  this.subdomain = this.trim().toLowerCase();
  next();
});

PS. I am also using mongoose-validator, which in turn uses node-validator to validate the user input - node validator also has some sanitize methods, maybe I should use them somehow?

Upvotes: 1

Views: 2917

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

In this case I think it would be better to add trim: true to the Organization schema definition for subdomain:

subdomain: { type: String, trim: true }

Upvotes: 2

Related Questions