简体   繁体   中英

How to trim spaces between words in mongoose?

How can i trim spaces between words in mongoose for my DB ? Lets imagine a case `

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/TodoApp', { useNewUrlParser: true });

const Todo = mongoose.model('Todo', {
  text: {
    type: String,
    required: true,
    minlength: 1,
    trim: true
  }
});

const newTodo = new Todo({
  text: "   Cook     dinner   "
});

newTodo .save().then((doc) => {
  console.log('Saved todo', doc)
}).catch((e) => {
  console.log(e);
});

If i run this code i will get a document in my db where the text value is`

"Cook     dinner"

But i would instead like to get

"Cook dinner"

How can i get this kind of result just with mongoose ?

Please check trim() definition in the docs, it seems like you're trying to remove unwanted characters in the middle of the string, but trim() removes them only at the start and at the end of the string ( Mongo docs )

I would suggest you to define a custom setter ( doc ) or preSave ( doc ) hook for this and transform string using regex (if you want to remove only spaces): str.replace( /\\s\\s+/g, ' ' )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM