User Routes
User.js controller
server
├── models
│ ├── User.js
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema(
{
firstName: {
type: String,
required: true,
min: 2,
max: 50,
},
lastName: {
type: String,
required: true,
min: 2,
max: 50,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 5,
},
picturePath: {
type: String,
default: "",
},
friends: {
type: Array,
default: [],
},
location: String,
occupation: String,
viewedProfile: Number,
impressions: Number,
},
{ timestamps: true }
);
const User = mongoose.model("User", UserSchema);
export default User;
- You are using mongoose, an Object Data Modeling (ODM) tool that helps you define and work with data in MongoDB.
- You are creating a UserSchema using the new mongoose.Schema() constructor. This schema maps to a MongoDB collection called “User” and defines the shape of the documents within that collection.
- Your schema has several properties, such as firstName, lastName, email, password, picturePath, friends, location, occupation, viewedProfile and impressions. Each property has a type option that specifies what kind of data it can store. For example:
firstName: {
type: String,
required: true,
min: 2,
max: 50,
},
This means that firstName can only store strings that are between 2 and 50 characters long and are required for every document.
- Some properties also have other options, such as required, default, min, max or unique. These options provide additional validation or functionality for your data. For example:
email: {
type: String,
required: true,
max: 50,
unique: true,
},
This means that email can only store strings that are up to 50 characters long and are required for every document. It also means that email must be unique across all documents in the collection.
- Your schema also has a timestamps option set to true. This means that mongoose will automatically add two fields called createdAt and updatedAt to your schema and manage them for you.
- Finally, you are creating a User model from your schema using the mongoose.model() function. This model is what you use to create, read, update or delete documents from the database.
const User = mongoose.model("User", UserSchema);
export default User;