mongoose model type object code example

Example 1: mongoose schema type

var schema = new Schema({
  name:    String,
  binary:  Buffer,
  living:  Boolean,
  updated: { type: Date, default: Date.now },
  age:     { type: Number, min: 18, max: 65 },
  mixed:   Schema.Types.Mixed,
  _someId: Schema.Types.ObjectId,
  decimal: Schema.Types.Decimal128,
  array: [],
  ofString: [String],
  ofNumber: [Number],
  ofDates: [Date],
  ofBuffer: [Buffer],
  ofBoolean: [Boolean],
  ofMixed: [Schema.Types.Mixed],
  ofObjectId: [Schema.Types.ObjectId],
  ofArrays: [[]],
  ofArrayOfNumbers: [[Number]],
  nested: {
    stuff: { type: String, lowercase: true, trim: true }
  },
  map: Map,
  mapOfString: {
    type: Map,
    of: String
  }
})

// example use

var Thing = mongoose.model('Thing', schema);

var m = new Thing;
m.name = 'Statue of Liberty';
m.age = 125;
m.updated = new Date;
m.binary = Buffer.alloc(0);
m.living = false;
m.mixed = { any: { thing: 'i want' } };
m.markModified('mixed');
m._someId = new mongoose.Types.ObjectId;
m.array.push(1);
m.ofString.push("strings!");
m.ofNumber.unshift(1,2,3,4);
m.ofDates.addToSet(new Date);
m.ofBuffer.pop();
m.ofMixed = [1, [], 'three', { four: 5 }];
m.nested.stuff = 'good';
m.map = new Map([['key', 'value']]);
m.save(callback);

Example 2: array schema mongoose

const ToySchema = new Schema({ name: String });
const ToyBoxSchema = new Schema({
  toys: [ToySchema],
  buffers: [Buffer],
  strings: [String],
  numbers: [Number]
  // ... etc
});

Example 3: mongoose custom object schema

var mongoose = require('mongoose');
Schema = mongoose.Schema;

var DishSchema = new mongoose.Schema({
  dishName: { type: String },
  tags:     { type: Array },
  price:    { type: Number },
  intro:    { type: String },
  dishPic:  { type: String },
  index:    { type: Number },
  comment:  { type: [{
    date:     {type: Date, default: Date.now },
    userId:   {type: String },
    content:  {type: String }
  }]}
});

var ShopSchema = new mongoose.Schema({
  shopName:       { type: String, unique: true },
  address:        { type: String },
  location:       { type: [Number], index: '2d' },
  shopPicUrl:     { type: String },
  shopPicTrueUrl: { type: String },
  mark:           { type: String },
  open:           { type: Boolean },
  shopType:       { type: String },
  dish:           { type: [DishSchema] },
  order:          { type: [{
    orderId:  { type: String },
    date:     { type: Date, default: Date.now },
    dish:     { type: [DishSchema] },
    userId:   { type: String }
  }]}
});

var Shop = mongoose.model('Shop', ShopSchema);
module.exports = Shop;