MongoDB-Mongoose-schema, model, CRUD


Defining Schema

An example

the key a property could have: type, required, unique, default, enum, trim, minlength, maxlength, min, max, validate

import mongoose from 'mongoose';
const { Schema } = mongoose;

const blogSchema = new Schema({
  title:  String, // String is shorthand for {type: String}
  author: {type: string, required: true, unique: true}
  gender: {type: string, enum: ['female', 'male']}
  body:   String,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now},
  hidden: Boolean,
  meta: {
    votes: Number,
    favs:  Number
  }
});

validate and required key

requried:

onst breakfastSchema = new Schema({
  eggs: {
    type: Number,
    min: [6, 'Too few eggs'],
    max: 12
  },
  bacon: {
    type: Number,
    required: [true, 'Why no bacon?']
  },
  drink: {
    type: String,
    enum: ['Coffee', 'Tea'],
    required: function() {
      return this.bacon > 3;
    }
  }
});

Permitted schema types

String

Number

Date

Buffer

Boolean

Mixed

ObjectId

Array

Decimal128

Map

Schema methods

Schema methods

Validation in schema

Pass a function to the required

const breakfastSchema = new Schema({
  eggs: {
    type: Number,
    min: [6, 'Too few eggs'],
    max: 12
  },
  bacon: {
    type: Number,
    required: [true, 'Why no bacon?']
  },
  drink: {
    type: String,
    enum: ['Coffee', 'Tea'],
    required: function() {
      return this.bacon > 3;
    }
  }
});

Use the validate

const userSchema = new Schema({
  phone: {
    type: String,
    validate: {
      validator: function(v) {
        return /\d{3}-\d{3}-\d{4}/.test(v);
      },
      message: props => `${props.value} is not a valid phone number!`
    },
    required: [true, 'User phone number required']
  }
});

Custom error messages

const breakfastSchema = new Schema({
  eggs: {
    type: Number,
    min: [6, 'Must be at least 6, got {VALUE}'],
    max: 12
  },
  drink: {
    type: String,
    enum: {
      values: ['Coffee', 'Tea'],
      message: '{VALUE} is not supported'
    }
  }
});

Model

Intro

Models are fancy constructors compiled from Schema definitions. An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database.

Create a model based on a schema

const Blog = mongoose.model('Blog', blogSchema);

Document

An instance of a model is called a document. Creating them and saving to the database is easy.

const Tank = mongoose.model('Tank', yourSchema);

const small = new Tank({ size: 'small' });
small.save(function (err) {
  if (err) return handleError(err);
  // saved!
});

// or

Tank.create({ size: 'small' }, function (err, small) {
  if (err) return handleError(err);
  // saved!
});

// or, for inserting large batches of documents
Tank.insertMany([{ size: 'small' }], function(err) {

});

Each model is associated with a connection (mongoose.model() use the default connection), if want to create a model on another connection, use:

const connection = mongoose.createConnection('mongodb://localhost:27017/test');
const Tank = connection.model('Tank', yourSchema);

RUD

https://mongoosejs.com/docs/queries.html


A u t h o r: Joe
P o l i c y: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source Joe !
Leave Your Comment Here
  TOC