const mongoose = require('mongoose'); const bcrypt = require('bcryptjs'); const userSchema = new mongoose.Schema({ googleId: { type: String, sparse: true, }, email: { type: String, required: true, unique: true, lowercase: true, }, username: { type: String, required: true, }, password: { type: String, required: function() { return !this.googleId; }, }, avatar: { type: String, default: '', }, createdAt: { type: Date, default: Date.now, }, }); userSchema.pre('save', async function(next) { if (!this.isModified('password')) return next(); if (this.password) { this.password = await bcrypt.hash(this.password, 10); } next(); }); userSchema.methods.comparePassword = async function(candidatePassword) { return await bcrypt.compare(candidatePassword, this.password); }; module.exports = mongoose.model('User', userSchema);