Building a Store with Vue – Part Eight : Mongoose Schemas & Models

As mentioned in part one of the series we are using Mongoose so we can work with schemas and models like we are used to working with relational database models.


We are still working inside the root directory slash api. So in ./api . This in case you get confused and start re-creating directories for models, controller and such.

Importing Mongoose

To import or require Mongoose using ES6 we can use the following at the top of our .model/index.js

// ES6 import instead of require
import mongoose, { Schema as _Schema, model as _model } from 'mongoose';
This is a lot different from the old school
const mongoose = require('mongoose');

but works just as well. You import Schema as alias _Schema from the module Mongoose. This alias you can then use in the prep part of the schema

Schema Preparation

To set up a new schema we do the following:
// split in multiple constants
const Schema = _Schema;
const model = _model.bind(mongoose);
const ObjectId = _Schema.Types.ObjectId;
This way we make the names for Schema, model and ObjectId shorter and easier to use

New Schemas

To now set up our own new schema we can use the following

const productSchema = Schema({
// One to many relationship
manufacturer: { type:ObjectId, ref:'Manufacturer'}


for the product. The word ref is used here to make a one to many relationship.

For the manufacture we can use

const manufacturerSchema = Schema({
  id: ObjectId,
  name: String,

Model Creation

Let’s create some models for our schemas

const Product = model('Product', productSchema);
const Manufacturer = model('Manufacturer', manufacturerSchema);

Export Module

To make models available to other parts of the project we can use:

module.exports = { Product, Manufacturer };

we could have used exports instead module.exports and achieved the same result.  But then we would have to have used it twice per model. See also Sitepoint article on Exports and Module Exports.

Jasper Frumau

Jasper has been working with web frameworks and applications such as Laravel, Magento and his favorite CMS WordPress including Roots Trellis and Sage for more than a decade. He helps customers with web design and online marketing. Services provided are web design, ecommerce, SEO, content marketing. When Jasper is not coding, marketing a website, reading about the web or dreaming the internet of things he plays with his son, travels or run a few blocks.