18

私はそのuserSchemaようなものを持っています:

var userSchema = new Schema({
    name: {
      type: String
    , required: true
    , validate: [validators.notEmpty, 'Name is empty']
    }
  , username: {
      type: String
    , required: true
    , unique: true
    , validate: [validators.notEmpty, 'Username is empty']
    }
});

フィールドはusername一意である必要があります。このユーザー名がデータベースに既に存在する場合、Mongoose はエラーをスローします。ただし、大文字と小文字を区別しないわけではありません。

大文字と小文字を区別しない一意のチェックを実現する唯一の方法は、コレクションに対してクエリを実行する独自の検証ルールを作成することであると考えるのは正しいですか? このような検証チェックを作成して、コレクションへの接続を増やしてもよろしいですか? についても同様のことを行う必要がありemailます。

4

9 に答える 9

18

使用についてはどうですか:

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

あなたの目的を達成するために?

于 2012-12-21T14:13:04.900 に答える
11

インデックスでの照合は、この問題を解決します。strength: 2

index: {
  unique: true,
  collation: {
    locale: 'en',
    strength: 2
  }
}

これをスキーマ作成コードに次のように配置します。

var userSchema = new Schema({
  ...
  username: {
    type: String,
    required: true,
    index: {
      unique: true,
      collation: { locale: 'en', strength: 2 }
    }
});

注:モデルのインデックスが更新されていることを確認してください。これは手動で行う必要がある場合があります。

于 2019-02-07T16:19:51.857 に答える
6

...クエリを実行するNodeJSのマングースを使用:

const countryName = req.params.country;

{ 'country': new RegExp(`^${countryName}$`, 'i') };

また

const countryName = req.params.country;

{ 'country': { $regex: new RegExp(`^${countryName}$`), $options: 'i' } };

// ^australia$

また

const countryName = req.params.country;

{ 'country': { $regex: new RegExp(`^${countryName}$`, 'i') } };

// ^turkey$

MongoDB で Mongoose ORM を使用した Javascript、NodeJS の完全なコード例

// get all customers that given country name
app.get('/customers/country/:countryName', (req, res) => {
    //res.send(`Got a GET request at /customer/country/${req.params.countryName}`);

    const countryName = req.params.countryName;

    // using Regular Expression (case intensitive and equal): ^australia$

    // const query = { 'country': new RegExp(`^${countryName}$`, 'i') };
    // const query = { 'country': { $regex: new RegExp(`^${countryName}$`, 'i') } };
    const query = { 'country': { $regex: new RegExp(`^${countryName}$`), $options: 'i' } };

    Customer.find(query).sort({ name: 'asc' })
        .then(customers => {
            res.json(customers);
        })
        .catch(error => {
            // error..
            res.send(error.message);
        });
});
于 2020-02-03T05:44:00.957 に答える
2

ノードでこれを行っているかどうかはわかりません。ただし、次のような npm を使用できます: https://github.com/blakehaswell/mongoose-unique-validatorコレクションのフィールドで一意の検証を確認します。別の方法として、新しいリクエストが来るたびにコレクションをチェックインすることもできます。 http://timstermatic.github.io/blog/2013/08/06/async-unique-validation-with-expressjs-and-mongoose/ こちらの資料を参照して、ケースに適した方法で使用できます。

于 2016-03-03T19:08:14.290 に答える
0

非常に簡単な解決策

username : {
        trim:true,
        //lowercase:true,

        type:String,
        required:[true, '{PATH} is required.'],
        match : [
            new RegExp('^[a-z0-9_.-]+$', 'i'),
            '{PATH} \'{VALUE}\' is not valid. Use only letters, numbers, underscore or dot.'
        ],
        minlength:5,
        maxlength:30,
        //unique:true

        validate : [
            function(un, cb){
                console.log(v);
                student.findOne({username:/^un$/i}, function(err, doc){
                    if(err) return console.log(err);
                    if(!_.isEmpty(doc)) return cb(false);
                    return cb(true);
                });
            },
            'Username already exists.'
        ]
    },

ここでは、非同期検証を使用し、student同じフィールドが存在するかどうかをモデルにチェックインしています。必要に応じて、明らかに正規表現を使用できます。

しかし、この方法はお勧めしません。頭に合わないだけです。

代わりに、アプローチに固執し、{ type: String, lowercase: true, trim: true, unique:true }必要に応じて元のユーザー名を他のフィールドにコピーします。

于 2016-07-10T11:15:27.437 に答える
-2

正規表現を使ってみてはどうでしょうか?

var pattern = [ /some pattern/, "{VALUE} is not a valid user name!" ];

{ type: String, match: pattern }

詳細な参照: http://mongoosejs.com/docs/api.html#schematype_SchemaType-required

于 2015-02-10T09:08:53.930 に答える