Skip to main content

Schema

What is a schema

  • Everything in Mongoose starts with a Schema
  • Each schema maps to a MongoDB collection and defines the shape of the documents within that collection

String

const mySchema = new mongoose.Schema({
name:String,
name:{type:String},
name:{type:String,required:true},
position:{type:String,default:'engineer'},
position:{type:String,minLength:5,maxLength:255},
gender:{type:String,enum:['male','female']},
name:{type:String,unique:true}
});

Number

const mySchema = new mongoose.Schema({
age:Number,
age:{type:Number},
age:{type:Number,required:true},
age:{type:Number,default:1},
age:{type:Number,min:0,max:999}
});

Date

const mySchema = new mongoose.Schema({
entryDate:Date,
entryDate:{type:Date},
entryDate:{type:Date,required:true},
entryDate:{type:Date,default:Date.now},
entryDate:{type:Date,min:'1900-01-01',max:'9999-12-31'}
});

Boolean

const mySchema = new mongoose.Schema({
isDone:Boolean,
isDone:{type:Boolean},
isDone:{type:Boolean,required:true},
isDone:{type:Boolean,default:false},
});

Array

const mySchema = new mongoose.Schema({
tags:[String],
tags:{type:[String]},
tags:{type:[String],required:true},
tags:{type:[String],default:'test'}
});

ObjectID

const mySchema = new mongoose.Schema({
custID:mongoose.ObjectId,
custID:{type:mongoose.ObjectId},
custID:{type:mongoose.ObjectId,required:true}
});

Buffer

const mySchema = new mongoose.Schema({
binData:Buffer,
binData:{type:Buffer},
binData:{type:Buffer,required:true}
});