'MongoError: E11000 duplicate key error collection when trying to Log In

I logged in with google in my app without problems, I logged out and when logged in again I got this error:

"MongoError: E11000 duplicate key error collection: myAppDB.users index: username_1 dup key: { username: "John Doe" }"

I'm not creating a new user with the same name, I'd just need to log in.

App.js

mongoose.set("useCreateIndex", true);

const userSchema = new mongoose.Schema({
  googleId: String,
  profileImage: String,
  myCollection: {
    type: Object,
    default: Object
  },
  games: {
    type: Object,
    default: Object
  }
});


userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);

const User = new mongoose.model("User", userSchema);

passport.use(new GoogleStrategy({
    clientID: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
    callbackURL: "http://localhost:3000/auth/google/myApp",
    userProfileUrl: "https://www.googleapis.com/oauth2/v3/userinfo",
    passReqToCallback: true
  },
  function(req, accessToken, refreshToken, profile, cb) {
    console.log(profile);
    User.findOrCreate({
        googleId: profile.id,
        username: profile.displayName,
        profileImage: profile.photos[0].value,
        myCollection: catalogDb,
        games: {}
      },
      function(err, user) {
        return cb(err, user);
      });
  }
));

passport.use(User.createStrategy());

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source