简体   繁体   English

如何修剪猫鼬中的单词之间的空格?

[英]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 ) 请检查docs中的trim()定义,似乎您正在尝试删除字符串中间的多余字符,但是trim()仅在字符串的开头和结尾删除它们( 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, ' ' ) 我建议您为此定义一个自定义的setterdoc )或preSavedoc )钩子,并使用regex转换字符串(如果只想删除空格): str.replace( /\\s\\s+/g, ' ' )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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