Building an e-Commerce website with Node – Part 27 – Create model for category and product in Node.js

Under the models folder create a new file and name it category.js. In this file, type the following code:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var CategorySchema = new Schema({
  name: { type: String, unique: true, lowercase: true}
});

module.exports = mongoose.model('Category', CategorySchema);

First, we have to import Mongoose library for creating Schema.
Then we have to create category schema and give it a name, which will be a string date, unique, and lowercase.
Once this is done, all we have to do is to export this Schema so it can be used in other files. The category model is completed.

Let’s create the model for product. Under the models folder create a new file and name it product.js. In this file type the following code:

var mongoose = require('mongoose');
var mongoosastic = require('mongoosastic');
var Schema = mongoose.Schema;

var ProductSchema = new Schema({
  category: { type: Schema.Types.ObjectId, ref: 'Category'},
  name: String,
  price: Number,
  image: String
});

module.exports = mongoose.model('Product', ProductSchema);

Again, we need Mongoose library so we require it.
Next we have to create the Product Schema.
Each product will belong to a category, will have a name (which will be a string), will have a price (which will be a number), and an image.

Of course, we have to export the Product Schema so it can be used in other files.

Note:
The ObjectId is the unique ID given by the database MongoDB.

Leave a Reply