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.
FYI
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';
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
// split in multiple constants const Schema = _Schema; const model = _model.bind(mongoose); const ObjectId = _Schema.Types.ObjectId;
New Schemas
To now set up our own new schema we can use the following
const productSchema = Schema({ id:ObjectId, name:String, image:String, price:Number, description:String, // 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.