简体   繁体   中英

Saving users into mongodb database

 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 isn't a bug - you just haven't defined googleId anywhere in your schema, so you are trying to add something which doesn't exist in the User Schema. Unfortunately, you do have to edit your schema to add the googleId data. If you want that you will 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 in your User.findOrCreate() function, it will create a User with the googleId as profile.id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM