44

The link is http://mongoosejs.com/docs/api.html#schema_string_SchemaString-trim

I'm beginner in mongoosejs. I just don't get it...

I saw this question How to update mongoose default string schema property trim? but don't understand why trim. Im creating my first schema today like a 'hello world'.

I saw this to https://stackoverflow.com/tags/trim/info ... but when i need to use it, i want to learn more about it. Im looking for an explanation for a beginner...

Vishwak
  • 323
  • 3
  • 11
Undefined Behavior
  • 2,128
  • 4
  • 24
  • 34

5 Answers5

118

It's basically there to ensure the strings you save through the schema are properly trimmed. If you add { type: String, trim: true } to a field in your schema, then trying to save strings like " hello", or "hello ", or " hello ", would end up being saved as "hello" in Mongo - i.e. white spaces will be removed from both sides of the string.

Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159
  • 8
    @bruno.karklis Read documents about javascript trim function. – damphat Dec 24 '13 at 20:32
  • @xpto Why this behave like that as normal javascript function won't behave the same – VIKAS KOHLI Dec 20 '18 at 06:16
  • @VIKASKOHLI because in that time i dint know the JS syntax well, i was learning, my background was SQL and PHP, and the thinking process is diferent, you dont use php syntax in SQL databade to do something. Besides that i knew that the database was made in JS, i was not aware that i could use JS syntax in the database. – Undefined Behavior Dec 20 '18 at 17:38
  • another question is that "should we really handle such things at DB level?" since it can be handled through server code. Are there any performance benefits? – manish keer Dec 16 '19 at 12:54
  • @UndefinedBehavior It you will add " hello world", its will be "hello world" – Deepak swain Dec 17 '19 at 07:19
3

Using trim will help in removing the white spaces present (beginning and ending of the string) in the string that you want to save to the DB like

"ABC " , "     ABC  ",

will be saved in the form

"ABC"
Sachin
  • 1,206
  • 12
  • 13
2
trim: true

will remove leading and trailing whitespaces so something like

" hello "

will be saved as

"hello"

0

Actually, we use trim in mongoose to remove white space in a string.

For example: without use trim or trim:false

"mong oose "

with use trim or trim:true

"mongoose"

Note: gain better experience to read mongoose doc.

Aziza Kasenova
  • 1,501
  • 2
  • 10
  • 22
Nayem37
  • 9
  • 3
  • As said in documentation: JavaScript strings have a trim() method that you can use to can use to remove leading and trailing whitespace from a string. Trim don't remove white space in the middle of words. so trimmed "mong oose " is "mong oose". Please check and fix – Mohamed Hamzaoui Aug 12 '23 at 23:12
-1

trim in mongoose use to remove the white spaces from the strings

Rahul
  • 85
  • 1
  • 2