3

I would like to have every string property have trim set to true by default. Is there a way?

?? mongoose.Schema.String -> default { trim: true }

var schema = new Schema({
  p1: { type: String },
  p2: { type: String, trim: true }
  p3: { type: String, trim: true }
  p4: { type: String }
});
Pavel Hlobil
  • 1,762
  • 1
  • 15
  • 22

2 Answers2

6

A good way to re-use common configurations for schema paths is to set them using a variable.

Like this:

var trimmedString = { type: String, trim: true };

var schema = new Schema({
  p1: trimmedString,
  p2: trimmedString,
  p3: trimmedString,
  p4: trimmedString
});

You could also return the definition from a function that sets defaults for you, but allows you two override things (or add other settings, like an index or default).

Like this:

(using the underscore library's defaults method)

var _ = require('underscore');

var stringType = function(ops) {
  return _.defaults(ops || {}, {
    type: String,
    trim: true
  });
}

var schema = new Schema({
  p1: stringType(),
  p2: stringType({ index: true }),
  p3: stringType({ default: "something" }),
  p4: stringType({ trim: false })
});
Jed Watson
  • 20,150
  • 3
  • 33
  • 43
-1

You can add a pre-processing function, as follows (MySchema is the name you called your schema):

MySchema.pre('save', function(next) {
  for (var fld in this) {
    this[fld] = trim(this[fld]);
  }
  next();
});

That should do it.

Scott Switzer
  • 1,064
  • 1
  • 15
  • 25
  • This is dangerous. You'll have problems unless all the properties in your schema are strings. At best you're re-writing every property in the document, every time it is saved, and at worse you're overriding data or causing errors because you've just set an array to trim(array). See my answer for a much safer method. – Jed Watson Sep 26 '13 at 12:30
  • plus, this would hit unnecessarily the performance of your operations, especially since Mongoose already provides a trim operation which would do it "automatically" and in a way non-intrusive. – Kat Lim Ruiz Jun 21 '20 at 19:59