const findOrCreate = require("mongoose-findorcreate");
// User schema
const userSchema = new mongoose.Schema({
provider: {
type: String,
required: true
},
email: String,
password: String
});
userSchema.plugin(findOrCreate);
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
//----google-Oauth -----
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/secrets",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
function(accessToken, refreshToken, profile, cb) {
User.findOrCreate({ provider: profile.provider, googleId: profile.id }, function (err, user) {
console.log(profile.id);
return cb(err, user);
});
}
));
I have 2 google accounts, when I signup/in with one, an id is saved on the database for the first account, but if I signup/in with the other, I'll will be able to log in too but the id won't save in the database whereas they both have different google-generated id if I log the profile.id into the console(I understand mongodb id generated is different from google's, but the second account's id is still not saved in the database). However, when I added id field into the userSchema(id: String, and I also set the value to profile.id in the findorcreate method), the two accounts were saved with both their database generated id and google id on the database. Is it that I can't register with two accounts without setting another id field in the user schema?
There's no error - you just haven't defined googleId anywhere in your schema, so you're trying to add something that doesn't exist in the user schema. Unfortunately, you have to edit your schema to add the googleId data. If you want, you'll have to edit your schema to something like this (as an example)
provider: { type: String, required: true }, email: String, password: String, googleId: {type: Number, required: false} This means that in your User.findOrCreate() function, you will create a User with the googleId as profile.id .