问题
I am using Node.js, MongoDB with Mongoose and am using passport.js for authentication.
Here is my user schema:
const userSchema = new mongoose.Schema({
email: String,
password: String,
googleId: String,
facebookId: String,
profilePic: String,
fName: String,
lName: String
});
And my google strategy:
passport.use(
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/dashboard",
profileFields: ["id", "displayName", "photos", "email"]
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
console.log(profile.photos[0].value);
User.findOrCreate(
{ googleId: profile.id },
{ profilePic: profile.photos[0].value },
{ email: profile.emails[0].value },
function(err, user) {
return cb(err, user);
}
);
}
)
);
When I console.log
my result I see my profile, along with profile photo url and profile email but I am unable to see my email id. Only 4 fields are getting created :
_id
googleId
profilePic
_v
Can someone tell me how to get the email field to save too?
回答1:
Why you are having the issue:
You are not using the findOrCreate
method well. findOrCreate
can take up to four arguments.findOrCreate(conditions, doc, options, callback)
:
conditions
: This is used to specify the selection-filter to find the document.doc
[optional]: If a document that matches the selection-filter(conditions
) is not found, thisdoc
is merged with what is you have inconditions
and then inserted into the DB.options
[optional]: From the plugin codebase, I figured you can useoptions.upsert
(if set totrue
) to update the document if it already exist.callback
: The function executed after the operation is done.
What you are doing wrong is passign { email: profile.emails[0].value }
as the third argument where options
is expected, you are supposed to include it in the doc
i.e the second argument.
The Fix
Try this:
passport.use(
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/dashboard",
profileFields: ["id", "displayName", "photos", "email"]
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
console.log(profile.photos[0].value);
User.findOrCreate(
{ googleId: profile.id },
// Notice that this function parameter below
// includes both the profilePic and email
{ profilePic: profile.photos[0].value, email: profile.emails[0].value },
function(err, user) {
return cb(err, user);
}
);
}
)
);
来源:https://stackoverflow.com/questions/60393424/mongoose-unable-to-create-more-than-4-fields-using-findorcreate