我可以将MongoDB中的必需属性设置为多语言吗

时间:2019-03-28 13:31:55

标签: node.js mongodb express mongoose

我正在为MongoDB中的用户创建模式,而我在这里面临的问题是Web应用将是多语言的,因此这意味着我正在用户模式中更具体地在后端进行验证,因此需要字段和唯一信息,如果出现问题,我会向用户显示该消息,因此,如果用户以其他语言使用该应用程序,则可以从此处更改消息并向他显示。

这是我正在使用的架构:

const UserSchema = new Schema({
  name: {
    type: String,
    trim: true,
    required: "Name is required"
  },
  surname: {
    type: String,
    trim: true,
    required: "Surname is required"
  },
  username: {
    type: String,
    trim: true,
    unique: "Username already exist",
    required: "Username is required"
  },
  email: {
    type: String,
    trim: true,
    unique: "Email already exists",
    match: [/.+\@.+\..+/, "Please fill a valid email address"],
    required: "Email is required"
  },
  password: {
    type: String,
    required: "Password is required"
  },
  role: {
    type: String,
    trim: true,
    required: "Role is required"
  }
});

1 个答案:

答案 0 :(得分:0)

const validationMessagesTranslation = (field, lang) => {
  const validationMessages = {
    "en": {
      name: "Name is required",
      surname: "Surname is required"
    },
    "fr": {
      name: "Le nom est requis.",
      surname: "Le nom de famille est requis."
    }
  }
  return validationMessages[lang][field];
}

您可以创建一个函数,其中包含需要的所有翻译的枚举。将该函数传递给模型的required值。