User Mongoose schemas
Course: PayTM project - chapter 2
We need to support 3 routes for user authentication
- Allow user to sign up.
- Allow user to sign in.
- Allow user to update their information (firstName, lastName, password).
To start off, create the mongo schema for the users table
- Create a new file (db.js) in the root folder
- Import mongoose and connect to a database of your choice
- Create the mongoose schema for the users table
- Export the mongoose model from the file (call it User)
Solution
Simple solution
const mongoose = require('mongoose');
// Create a Schema for Usersconst userSchema = new mongoose.Schema({ username: String, password: String, firstName: String, lastName: String});
// Create a model from the schemaconst User = mongoose.model('User', userSchema);
module.exports = { User};Elegant Solution
const mongoose = require('mongoose');
// Create a Schema for Usersconst 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 schemaconst User = mongoose.model('User', userSchema);
module.exports = { User};