Schema

npm install mongoose -S
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myappdatabase');

Simple Schema

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 
var customerSchema = new Schema({ 
    name:      String, 
    address:   String, 
    city:      String, 
    state:     String, 
    country:   String, 
    zipCode:   Number, 
    createdOn: Date, 
    isActive:  Boolean 
}); 

var simpleSchema = new Schema({ fieldName: SchemaType });

Complex Schema

Alowed Data Type

Mongoose Schema Type

Javascript Data Type

String

String

Number

Number

Boolean

Boolean

Date

Object

Buffer

Object

Mixed

Object

ObjectId

Object

Array

Array(Object)

Adding custom method

Using custom method

Run a Function Before Saving

Here is the code to add to our Schema to have the date added to created_at if this is the first save, and to updated_at on every save

Last updated

Was this helpful?