Answer a question

I have my schema:

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

And i know that mongoose have some methods to help me uppercase, lowercase, even trim my String, but what about capitalize? I want be me able to uppercase only the firsts letters of the name and the email.

How can i do that??

I am using a form to catch the data, them save in my database using a post route, and there are some users that type all lowecase, and i was trying deal with this problem with css.

input#name {
 text-transform: capitalize;
}

But this not work.

Answers

CSS Styles are only on the visible side, not on the data side.

You have to use Javascript to do this:

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

Edit: As Luis Febro mentioned in the comments underneath, the current implementation keeps the upper/lowercase spelling of the rest of the string. If you really want to make sure, that there is only the first letter capitalized and the rest is built out of lowercase letters, you could adjust the code like this:

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

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐