Episode 13 of 21

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:

  1. Go to your cluster in MongoDB Atlas
  2. Click Collections
  3. Find the users collection
  4. 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

MethodReturnsUse Case
findOne(query)Single document or nullFind a specific user
findById(id)Single document by _idFind by MongoDB ID
find(query)Array of documentsFind 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 query
  • findById() is a shortcut for finding by the _id field
  • The check-then-create pattern prevents duplicate user records