|
| 1 | +Mongoose has a `trim()` [SchemaType option](https://mongoosejs.com/docs/schematypes.html#schematype-options) that registers a [setter](https://mongoosejs.com/docs/tutorials/getters-setters.html) which automatically [trims](/tutorials/fundamentals/trim-string) leading and trailing whitespace from the given string. |
| 2 | +[Whitespace](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace) includes spaces, newlines `\n`, tabs `\t`, carriage return `\r`, and others. |
| 3 | + |
| 4 | +```javascript |
| 5 | +const userSchema = new Schema({ |
| 6 | + name: { |
| 7 | + type: String, |
| 8 | + trim: true // Registers a setter which calls `trim()` automatically |
| 9 | + } |
| 10 | +}); |
| 11 | +const UserModel = mongoose.model('User', userSchema); |
| 12 | + |
| 13 | +const user = new User({ name: ' da Vinci ' }); |
| 14 | +user.name; // 'da Vinci', without leading and trailing spaces |
| 15 | +``` |
| 16 | + |
| 17 | +Whenever you set `user.name` in the above example, Mongoose will automatically call `trim()` to trim leading and trailing whitespace from the user's `name`. |
| 18 | +This ensures that any new `name` properties you save to your database will have no leading or trailing whitespace. |
| 19 | + |
| 20 | +Mongoose will also `trim()` the `name` property in your query filters by default. |
| 21 | +So if you run a query by `name`, Mongoose will `trim()` the name by default. |
| 22 | + |
| 23 | +```javascript |
| 24 | +// The following is equivalent to querying by `{ name: 'da Vinci' }` |
| 25 | +// because Mongoose will `trim()` the `name` property. |
| 26 | +await UserModel.findOne({ name: ' da Vinci ' }); |
| 27 | +``` |
| 28 | + |
| 29 | +## Caveat: `trim` is Setter Only, No Getter |
| 30 | + |
| 31 | +`trim()` is a setter, so if you have existing documents in your database with leading or trailing whitespace, Mongoose will not `trim()` that whitespace when loading the document from MongoDB. |
| 32 | + |
| 33 | +```javascript |
| 34 | +const _id = new mongoose.Types.ObjectId(); |
| 35 | +// Insert a document with leading and trailing whitespace, bypassing Mongoose |
| 36 | +await UserModel.collection.insertOne({ _id, name: ' da Vinci ' }); |
| 37 | + |
| 38 | +const doc = await UserModel.findById(_id); |
| 39 | +doc.name; // ' da Vinci ', with leading and trailing whitespace |
| 40 | +``` |
| 41 | + |
| 42 | +To apply the setter, you can set the document's `name` to itself as follows. |
| 43 | + |
| 44 | +```javascript |
| 45 | +// The following triggers Mongoose's setters, so will apply `trim()`. |
| 46 | +doc.name = doc.name; |
| 47 | + |
| 48 | +doc.name; // 'da Vinci', no leading or trailing whitespace |
| 49 | +await doc.save(); // Persist the document's new `name` |
| 50 | +``` |
0 commit comments