Episode 12 of 21
Saving User to MongoDB
Save new users to the database from the Passport callback — check if the user exists first, and only create a new record for first-time users.
Saving User to MongoDB
Now let us connect the Passport callback to the database. When a user logs in, you should check if they already exist. If they do, use the existing record. If not, create a new one.
Updated Passport Callback
// config/passport-setup.js
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const keys = require('./keys');
const User = require('../models/user-model');
passport.use(
new GoogleStrategy({
clientID: keys.google.clientID,
clientSecret: keys.google.clientSecret,
callbackURL: '/auth/google/redirect'
}, function(accessToken, refreshToken, profile, done) {
// Check if user already exists
User.findOne({ googleId: profile.id }).then(function(currentUser) {
if (currentUser) {
// User exists — use existing record
console.log('User already exists:', currentUser);
done(null, currentUser);
} else {
// User does not exist — create new
new User({
username: profile.displayName,
googleId: profile.id,
thumbnail: profile.photos[0].value
}).save().then(function(newUser) {
console.log('New user created:', newUser);
done(null, newUser);
});
}
});
})
);
The Logic Flow
Passport callback fires with Google profile
↓
Search database for googleId
↓
┌─── Found? ──────────────────────┐
│ YES: Use existing user │
│ NO: Create new user, save to DB│
└─────────────────────────────────┘
↓
Call done(null, user)
↓
Passport continues with session setup
What Gets Stored in MongoDB
{
"_id": "5a1b2c3d4e5f6g7h8i9j",
"username": "Shaun Pelling",
"googleId": "123456789012345678901",
"thumbnail": "https://lh3.googleusercontent.com/photo.jpg",
"__v": 0
}
Key Takeaways
- Always check if the user exists before creating a new record
- Use
googleIdto identify returning users — it is unique per Google account - Call
done(null, user)with the user object (new or existing) to continue the flow - First login creates a record; subsequent logins find and reuse it