0

I'm making a project with node, mongoose and express.

I have this schema in mongoose

const userSchema = new Schema({
  local: {
    email: {
      type: String,
      lowercase: true,
      unique: true,
      ....
    },
    password: {
      type: String
    }
  },
  google: {
    googleId: String,
    email: String
  },
  ....
};

Because i have two passport strategies (local for the classic email, password and google).

But when i create two accounts with different google accounts. The console shows me this error:

{ MongoError: E11000 duplicate key error collection: xxx.users index: local.email_1 dup key: { : null }

WHAT?? The "Unique" detect duplicated two undefined values?

So. How can i avoid this?

Thank you :)

nano
  • 51
  • 7
  • Possible dupe of https://stackoverflow.com/questions/7955040/mongodb-mongoose-unique-if-not-null – JohnnyHK Apr 04 '17 at 20:25
  • Nope. unique: true, sparse: true don't worked (same MongoError). – nano Apr 04 '17 at 20:34
  • Did you drop the existing index first? – JohnnyHK Apr 04 '17 at 20:35
  • Yes. I'm deleted all the collections with robomongo. Then i put this in my schema. local: { email: { type: String, lowercase: true, unique: true, sparse: true, .... }, And i have the same error with two accounts created with google: { MongoError: E11000 duplicate key error collection: xxx.users index: local.email_1 dup key: { : null } – nano Apr 04 '17 at 20:41
  • Sounds like you're passing an actual value of `null` for that field. Just omit the `local.email` field in your doc when it isn't used. – JohnnyHK Apr 04 '17 at 20:44
  • Is ommited. const user = new User({ profile: { firstName: profile.name.givenName }, google: { googleId: profile.id, email: profile.emails[0].value } }); So. Mongodb detect two undefined local.email values and throw the stupid error. – nano Apr 04 '17 at 20:47
  • What's in the `....` for that field of the schema? You don't have `default: null` there do you? – JohnnyHK Apr 04 '17 at 20:48
  • ... is the rest of schema. default: null don't worked – nano Apr 04 '17 at 20:52

1 Answers1

0

hello i just solved the error all you got to do is to go to Robomongo and in your collections i think is users open it you will find indexex delete the one who gave you the error the it solved

Mifayo
  • 73
  • 8