0

This is my User schema:

    const UserSchema = Schema({
      username: { 
        type: String,
        required: 'Username required.',
        unique: true
      },
      email: { 
        type: String,
        required: 'Email required.',
        unique: true
      },
      password: { 
        type: String, 
        required: 'Password required'
      },
      saltSecret: { 
        type: String 
      },
    }, {
      timestamps: true,
      versionKey: false
    });

It's possible to save documents with duplicated username or email.

I solved that running this command in mongo shell:

    db.users.createIndex({username: 1}, {unique: true});
    db.users.createIndex({email: 1}, {unique: true});

I would like to solve this using mongoose. How to do that?. Thanks in advance.

tornadoradon
  • 400
  • 1
  • 8
  • 17
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
  • This code used to works fine, the only change i made it is to convert nodejs modules syntax to import/export syntax. – sonEtLumiere Mar 07 '23 at 01:06
  • when you have done with createIndex part, you will get an error when you trying to duplicate value. the problem, sometimes you need to rerun the indexing when you createIndex after you already have some documents in database – Tobok Sitanggang Mar 07 '23 at 03:12
  • and if you want to handle it with mongoose, you can use `findOneOrUpdate` with option `upsert: false` – Tobok Sitanggang Mar 07 '23 at 03:14
  • can you check if duplicates already existed? https://stackoverflow.com/questions/5535610/mongoose-unique-index-not-working it might help – rohanraj Mar 07 '23 at 04:35

1 Answers1

1

Try with index:

const UserSchema = new Schema({
  username: { 
    type: String,
    required: 'Username required.',
    unique: false
  },
  email: { 
    type: String,
    required: 'Email required.',
    unique: false
  },
  password: { 
    type: String, 
    required: 'Password required'
  },
  saltSecret: { 
    type: String 
  },
}, {
  timestamps: true,
  versionKey: false
});

UserSchema.index({ username: 1, email: 1 }, { unique: true });
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29