【问题标题】:Validate unique username验证唯一用户名
【发布时间】:2013-07-09 00:08:27
【问题描述】:

我正在尝试使用猫鼬来验证用户模型的用户名字段的唯一性

User.schema.path('username').validate(function(value, done) {
  User.findOne({username: value}, function(err, user) {
    if (err) return done(false);
    if (user) return done(false);

    done(true);
  });
}, "exists");

当我创建新用户时,这一切都很好。但是,当更新用户数据时,我的验证失败。基本上是因为我试图编辑同一个用户,所以验证失败。 IE。更新用户名 = bob 时,验证方法找到 bob 并失败。

我在该字段的模型上有 unique: true ,因此 mongodb 无需我的 mongoose 验证就可以很好地验证它。

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

但是,让 mongo 告诉我我无法插入数据的问题是没有很好的方法来提取有意义的错误消息以发送回客户端。即'对不起用户名已经存在,请选择一个新的'

基本上我能想到的解决这个问题的唯一方法是,如果 mongoose 向我的验证器传递了我要验证的实际对象,而不仅仅是值。然后我可以比较_id,即

if (current._id == new._id) //this is the same user don't fail validation on unique username

【问题讨论】:

标签: node.js mongoose


【解决方案1】:

有一个很好的 mpn 模块用于 mongoose 唯一性验证:https://github.com/blakehaswell/mongoose-unique-validator

【讨论】:

    猜你喜欢
    • 2017-11-02
    • 2016-06-26
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 2018-04-13
    • 2021-02-25
    相关资源
    最近更新 更多