MongoDB Schema & Model

In MongoDB + Mongoose, you normally create a model in two steps:

  1. Define a Schema
  2. Create a Model from that schema


For example, let’s create a User model.

import { Schema, model } from "mongoose";

const userSchema = new Schema({
	name: {
    	type: String,
    	required: true
	},
	email: {
    	type: String,
    	required: true,
    	unique: true
	}
}, {
	timestamps: true
});

export default model("User", userSchema);

Schema defines the structure of a user document, export allows you to use the model in other files.

For detail review, please have look as follow.

https://github.com/KoolMonk/mern-alfa/blob/master/server/models/User.js