Mongoose ~ Schema - rohit120582sharma/Documentation GitHub Wiki

Defining a schema

Everything in Mongoose starts with a Schema. Each schema defines the shape/structure of documents in a MongoDB collection. A collection in MongoDB is like a table and a document is kind of similar to a row in a relational database.

Each key in the schema defines a property in documents which will be cast to its associated SchemaType. Keys may also be assigned nested objects containing further key/type definitions.

Supported types are: String, Number, Date, Buffer (for storing binary data), Boolean and ObjectID.

Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor. The type assigned is an ObjectId to coincide with MongoDB's default behavior. ObjectId schema type is the common syntax for creating a primary key in Mongoose and MongoDB.

Mongoose will, by default, "minimize" schemas by removing empty objects. This behavior can be overridden by setting minimize option to false. It will then store empty objects.

const mongoose = require('mongoose');

// Author shcema
const authorSchema = new mongoose.Schema(
    {
        name: {
            firstName: {
                type: String,
                required: true
            },
            lastName: {
                type: String,
                required: true
            }
        },
        biography: {
            type: String
        },
        profilePicture: {
            type: Buffer
        },
        created: { 
            type: Date,
            default: Date.now
        },
        tags: [String]
    },
    {
        minimize: false,
        timestamp: true
    }
);

module.exports = authorSchema;


Creating and saving models

Once we have schema, we need to compile that into a Model. A model is a class with which we construct documents.

The mongoose.model() method takes two arguments. The first argument is the singular name of the collection that this model is for. The second argument is the schema that defines the shape of documents in this collection.

Next we can create an instance object based on that class, and this object maps to a document in MongoDB database.

The created object has a method called save(). Here we're dealing with an asynchronous operation, because it's going to take some time to save this course to the database, because we are going to access the file system.

MongoDB assigns a unique identifier to the object when saved as document in the collection.

// Create Author model
const Author = mongoose.model('author', authorSchema);

// Create a document (an instance) using Author model
const author = new Author({
    name: {
        firstName: 'Rohit',
        lastName: 'Sharma'
    },
    biography: 'My story',
    tags: ['vaporizing', 'talking']
});

// Save the document
author.save()
    .then(data => console.log(data))
    .catch(err => console.error(err));


Association with nested schema

Create two schemas that will demonstrate how to create a relationship to another schema: "author" and "book". The book schema will contain a reference to the author by using the ObjectId schema type.

Referencing documents (normalization) is a good approach when you want to enforce data consistency. Because there will be a single instance of an object in the database.

const mongoose = require('mongoose');

// Book Schema
var bookSchema = new mongoose.Schema(
    {
        title: {
            type: String,
            unique: true,
            required: true
        },
        summary: {
            type: String
        },
        thumbnail: {
            type: Buffer
        },
        tags: [ String ],
        isPublished: {
            type: Boolean,
            default: false
        },
        author: {
            type: mongoose.Schema.Types.ObjectId,
            required: true,
            ref: 'author'
        },
    },
    {
        timestamp: true
    }
);

module.exports = bookSchema;


⚠️ **GitHub.com Fallback** ⚠️