【问题标题】:Add property to mongoose document pre lowercase validation将属性添加到猫鼬文档预小写验证
【发布时间】:2023-03-21 09:43:01
【问题描述】:

我希望用户对象保持区分大小写以用于显示目的,但为了唯一性目的而将其小写。我的第一个想法是在架构中添加 usernameDisplay 属性并尝试预保存挂钩:

var userSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true,
        lowercase: true
    },
    usernameDisplay: String,
    password: {
        type: String,
        required: true
    }
});

userSchema.pre("save", function (next) {
    this.usernameDisplay = this.username;
    next();
});

但这似乎不起作用。 usernameusernameDisplay 属性都保存为小写用户名。

我认为以下方法可行:删除架构中的 lowercase 验证并执行此操作:

userSchema.pre("save", function (next) {
    this.userDisplayName = this.username;
    this.username = this.username.toLowerCase();
    next();
});

但现在我很好奇 Mongoose 如何对传入数据进行小写验证/更改。

如果我的问题不清楚,请告诉我,我可以尝试更新它以澄清问题。

【问题讨论】:

    标签: javascript node.js mongoose


    【解决方案1】:

    您可以在猫鼬模型中应用小写:

    stuff: { type: String, lowercase: true, trim: true }
    

    https://mongoosejs.com/docs/4.x/docs/schematypes.html

    【讨论】:

      【解决方案2】:

      首先,我认为 mongoose 没有小写验证,它似乎相当具体。

      其次,你的方法对我来说似乎很好。但是我推荐使用 mongoose virtuals(这是 virtuals application 的教科书示例)。 简短参考:虚拟是不存储但每次计算的字段。所以你可以做这样的事情

      userSchema.virtual('userDisplayName').get(function(){
          return this.username.toLowerCase();
      });
      

      使用“userDisplayName”将是透明的,但不会存储该字段。

      最后但同样重要的是,关于您的代码,由于这一行,它在数据库中保存了相同的数据

      this.userDisplayName = this.username;
      

      您正在为同一个引用分配 2 个名称,因此更改一个名称会更改另一个名称。不如试试这个。

      this.userDisplayName = this.username.toLowerCase();
      next(); 
      

      希望对你有帮助

      【讨论】:

      • 关于this.userDisplayName = this.username - 我假设因为用户名是一个字符串,并且字符串是按值而不是引用传递的,所以改变一个不应该改变另一个。这是不正确的吗?此外,模式的字段确实有一个“小写”选项。也许“验证”是错误的词,因为它只是自动将任何输入小写。 mongoosejs.com/docs/schematypes.html
      • 另外,我想将数据库中的用户名保存为用户提交的所有内容的全小写版本。这样,无论用户输入什么,unique: true 验证都会生效。但我仍然希望能够以用户最初输入的大写字母显示用户名。我认为你的例子倒退了。
      • 好的,抱歉我弄错了。我刚刚检查了猫鼬文档,你是对的,有一个小写选项可以强制字段为小写。它似乎完全符合您的需要。但是,我会尝试对this.userDisplayName = this.username 进行修改,因为如果不是这样,我看不出它有任何其他原因。
      • 我想我只是对 何时 mongoose 小写的东西感到好奇,因为我的第一次尝试没有奏效。也许由于某种原因,字符串在该实例中没有按值传递。哦,好吧,没什么大不了的。我现在会坚持我的第二个解决方案。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2016-06-08
      • 2015-10-10
      • 1970-01-01
      • 2011-11-14
      • 2021-06-07
      • 2018-09-08
      • 2016-06-17
      • 2021-09-08
      相关资源
      最近更新 更多