Retrieving Users
Query the MongoDB database to find and retrieve user records — verify that users are being stored correctly after Google OAuth login.
Retrieving Users
Now that users are being saved to MongoDB, let us verify the data is correct and learn how to query for users using Mongoose.
Checking the Database
After logging in via Google, check your MongoDB Atlas dashboard:
- Go to your cluster in MongoDB Atlas
- Click Collections
- Find the
userscollection - You should see documents with username, googleId, and thumbnail
Mongoose Query Methods
// Find one user by Google ID
User.findOne({ googleId: '123456' }).then(function(user) {
console.log(user);
});
// Find one user by MongoDB ID
User.findById('5a1b2c3d4e5f...').then(function(user) {
console.log(user);
});
// Find all users
User.find({}).then(function(users) {
console.log(users);
});
Common Query Methods
| Method | Returns | Use Case |
|---|---|---|
findOne(query) | Single document or null | Find a specific user |
findById(id) | Single document by _id | Find by MongoDB ID |
find(query) | Array of documents | Find multiple users |
Duplicate Prevention
// First login: findOne returns null → create new user
// Second login: findOne returns the user → reuse existing
User.findOne({ googleId: profile.id }).then(function(currentUser) {
if (currentUser) {
// Already in DB — do not create again
done(null, currentUser);
} else {
// Not in DB — create
new User({ ... }).save().then(function(newUser) {
done(null, newUser);
});
}
});
Key Takeaways
- Use MongoDB Atlas dashboard to visually inspect stored documents
findOne()returns a single document matching the queryfindById()is a shortcut for finding by the_idfield- The check-then-create pattern prevents duplicate user records