Skip to content

User Mongoose schemas

Course: PayTM project - chapter 2

We need to support 3 routes for user authentication

  1. Allow user to sign up.
  2. Allow user to sign in.
  3. Allow user to update their information (firstName, lastName, password).

To start off, create the mongo schema for the users table

  1. Create a new file (db.js) in the root folder
  2. Import mongoose and connect to a database of your choice
  3. Create the mongoose schema for the users table
  4. Export the mongoose model from the file (call it User)
Solution

Simple solution

backend/db.js
const mongoose = require('mongoose');
// Create a Schema for Users
const userSchema = new mongoose.Schema({
username: String,
password: String,
firstName: String,
lastName: String
});
// Create a model from the schema
const User = mongoose.model('User', userSchema);
module.exports = {
User
};

Elegant Solution

backend/db.js
const mongoose = require('mongoose');
// Create a Schema for Users
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
lowercase: true,
minLength: 3,
maxLength: 30
},
password: {
type: String,
required: true,
minLength: 6
},
firstName: {
type: String,
required: true,
trim: true,
maxLength: 50
},
lastName: {
type: String,
required: true,
trim: true,
maxLength: 50
}
});
// Create a model from the schema
const User = mongoose.model('User', userSchema);
module.exports = {
User
};