Making a User Model
Create a Mongoose model for users — define the schema that determines what user data is stored in MongoDB.
Making a User Model
A Mongoose model defines the structure of documents in a MongoDB collection. It tells MongoDB what data to store for each user.
The User Schema
// models/user-model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: String,
googleId: String,
thumbnail: String
});
const User = mongoose.model('user', userSchema);
module.exports = User;
Schema Fields
| Field | Type | Purpose |
|---|---|---|
username | String | The user's display name from Google |
googleId | String | The unique ID Google assigns to the user |
thumbnail | String | URL of the user's Google profile photo |
Why googleId?
The googleId is unique to each Google account. When a user logs in again, you can look up their record by this ID instead of creating a duplicate. This is how you know if a user is new or returning.
How Mongoose Models Work
// Creating a new user
var newUser = new User({
username: 'Shaun',
googleId: '123456789',
thumbnail: 'https://photo.url'
});
// Save to MongoDB
newUser.save().then(function(savedUser) {
console.log('User saved:', savedUser);
});
// Find a user
User.findOne({ googleId: '123456789' }).then(function(user) {
console.log('Found:', user);
});
Key Takeaways
- A Mongoose Schema defines the structure of documents in a collection
mongoose.model('name', schema)creates a model you can use to read and write data- Store the Google ID to identify returning users
- Models provide methods like
save(),findOne(), andfind()for database operations