我如何将猫鼬中的字符串大写?

How can i capitalize strings in mongoose?

我有我的模式:

Schema = {
 name: String,
 email: String,
 animal: String
};

而且我知道 mongoose 有一些方法可以帮助我大写、小写,甚至 trim 我的字符串,但是大写呢?我希望我只能将姓名和电子邮件的首字母大写。

我该怎么做?

我正在使用一个表单来捕获数据,它们使用 post 路由保存在我的数据库中,并且有一些用户键入所有小写字母,我正在尝试使用 [= 处理这个问题22=].

input#name {
 text-transform: capitalize;
}

但这行不通。

CSS样式只在可见的一面,不在数据的一面。

您必须使用 Javascript 来执行此操作:

schema.pre('save', function (next) {
  // capitalize
  this.name.charAt(0).toUpperCase() + this.name.slice(1);
  next();
});

编辑: 正如 Luis Febro 在下面的评论中提到的,当前的实现保留了字符串其余部分的 upper/lowercase 拼写。如果你真的想确定,只有第一个字母大写,其余的都是小写字母,你可以这样调整代码:

this.name.charAt(0).toUpperCase() + this.name.slice(1).toLowerCase()

当您在 JavaScript 中输出名称时,您可以创建一个名称大写的新字符串。

var capName = user.name[0].toUpperCase() + user.name.slice(1);

这会将第一个字母大写并将其与字符串的其余字母组合以将单词大写并将其保存在新变量中。

最好的方法是使用 Mongooses Baked in functionality - 这应该可以做到!

Schema = {
 name:{
    type: String,
    uppercase: true
 },
 email: String,
 animal: String
};

来自 mongoose doc hereString 子部分下,您将找到可以应用于您的模式选项的所有函数。

Schema = {
 email: {type: String, lowercase: true, trim: true},
 animal: {type: String}
};

最佳做法

schema.pre("save", function(next) {
  this.name =
    this.name.trim()[0].toUpperCase() + this.name.slice(1).toLowerCase();
    next();
});

要将字符串中的所有单词大写,您可以试试这个...

personSchema.pre('save', function (next) {
  const words = this.name.split(' ')
  this.name = words
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
    .join(' ')
  next()
})

如果你有一个复合名称很有用... 'john doe' => 'John Doe'