Build an Online Shop with Vue

Schemas & Models

To interact with a MongoDB database via mongoose expressively, you need to define schemas and models. They just tell mongoose what the data structure looks like and the data types. This way, you have a more structured and organized way of writing to the database.

To define a schema, we make use of the mongoose.Schema method:

// ./model/index.js
const mongoose = require('mongoose');
const Schema   = mongoose.Schema,
      model    = mongoose.model.bind(mongoose),
      ObjectId = mongoose.Schema.Types.ObjectId;

const productSchema = Schema({
  id: ObjectId,
  name: String,
  image: String,
  price: Number,
  description: String,
  // One to many relationship
  manufacturer: {type: ObjectId, ref: 'Manufacturer'}
});

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

A schema takes an object that describes the data structure and types. There is a special type known as ObjectId which serves as unique ID for our stored items.

You can also create a one to many relationship using the ref property as shown in the example above. The ref value must be the model that we are setting the relationship with.

Speaking of models, let's create some for the defined schemas:

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

You can export the model to be used by other parts of our project:

module.exports = {Product, Manufacturer};