Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使用自定义验证从Mongoose架构中删除生成的字符串_Node.js_Mongoose_Schema - Fatal编程技术网

Node.js 使用自定义验证从Mongoose架构中删除生成的字符串

Node.js 使用自定义验证从Mongoose架构中删除生成的字符串,node.js,mongoose,schema,Node.js,Mongoose,Schema,我有一个带有自定义验证的模式 const schema=newmongoose.schema({ 用户名:{ 类型:字符串, 要求:正确, 验证:{ 验证器:/^[a-zA-Z0-9}{3,16}$/,, 消息:“用户名的长度必须为3到16个字符,并且仅包含字母数字字符和下划线(33;)。” }, }, //…其他事情 }); 但是,当我键入无效用户名时,验证消息如下所示: User validation failed: username: Usernames must be 3 to 16

我有一个带有自定义验证的模式

const schema=newmongoose.schema({
用户名:{
类型:字符串,
要求:正确,
验证:{
验证器:/^[a-zA-Z0-9}{3,16}$/,,
消息:“用户名的长度必须为3到16个字符,并且仅包含字母数字字符和下划线(33;)。”
},
},
//…其他事情
});
但是,当我键入无效用户名时,验证消息如下所示:

User validation failed: username: Usernames must be 3 to 16 characters long and contain only alphanumeric characters and underscores (_).

如何去掉字符串开头表示
用户验证失败:用户名:

格式已嵌入到。除了给那个类打补丁,我看不到一个简单改变格式的方法

一个选项是在模型抛出之前运行验证:

const user = new User({ username: 'ab' })
const error = user.validateSync()
console.log(error.errors['username'].message)
或在捕获时处理
ValidationError

try {
  const user = new User({ username: 'ab' })
  await user.save()
} catch (error) {
  if (error instanceOf mongoose.Document.ValidationError ) {
    console.log(error.errors['username'].message)
  }
}

要去除初始字符串,只需在显示返回的字符串之前对其使用split方法即可。下面是一个示例代码:

let stringa = "User validation failed: username: Usernames must be 3 to 16 characters long and contain only alphanumeric characters and underscores (_)."; //replace this with error message
let stringb = (stringa.split(":")[2]);

console.log(stringb);//This displays the needed output string with Usernames