如何在不创建 empty/null 字符串的情况下存储多个 Oauth2 id?

How do store multiple Outh2 ids without creating and empty/null string?

我正在尝试创建一个基本应用程序,您可以在其中通过 email/password 或使用 Google 或 Facebook Oauth2 注册,将必要的内容保存在 mongoDB 中。当您尝试从多个 google 或 Facebook 帐户访问应用程序时会出现问题。 (500 内部服务器错误)我知道问题是通过使用 Oauth2 我创建了一个空/空字符串,并且在 mongoDB 中由于索引(我不完全理解)它会导致错误。请查看我的代码,我删除了不必要的行以使其更短。这是数据库的屏幕截图:DBscreenshot

const userSchema = new mongoose.Schema({
  email: String,
  password: String,
  googleId: String,
  facebookId: String,
  secret: Array
});

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

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

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);
  });
});

passport.use(new GoogleStrategy({
    clientID: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
    callbackURL: "https://app-secret.herokuapp.com/auth/google/secrets",
    userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
  },
  function(accessToken, refreshToken, profile, cb) {
    // console.log(profile);
    User.findOrCreate({
      googleId: profile.id
    }, function(err, user) {
      return cb(err, user);
    });
  }
));

passport.use(new FacebookStrategy({
    clientID: process.env.FACEBOOK_APP_ID,
    clientSecret: process.env.FACEBOOK_APP_SECRET,
    callbackURL: "https://app-secret.herokuapp.com/auth/facebook"
  },
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({
      facebookId: profile.id
    }, function(err, user) {
      return cb(err, user);
    });
  }
));

app.get("/auth/google",
  passport.authenticate('google', {
    scope: ["profile"]
  })
);

app.get("/auth/google/secrets",
  passport.authenticate('google', {
    failureRedirect: "/login"
  }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/secrets');
  });

app.get('/auth/facebook',
  passport.authenticate('facebook'));

app.get('/auth/facebook/secrets',
  passport.authenticate('facebook', {
    failureRedirect: '/login'
  }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/secrets');
  });

app.post("/register", function(req, res) {
  User.register({
    username: req.body.username <----i assume this is the issue as using Oauth2 it will be null
  }, req.body.password, function(err, user) {
    if (err) {
      console.log(err);
      res.redirect("/register")
    } else {
      passport.authenticate("local")(req, res, function() {
        res.redirect("/secrets")
      })
    }
  })
});

虽然这不是一种“优雅”的方式,但最终我克服了为用户名分配变量的问题,即使它们t need to have one as they were using Oauth.. Like this the string won不是空的或空的,所以mongoDB最终让更多用户从 google 和 facebook 注册。