Defining a Product model

Products will be stored in a product collection in the database. To implement this, we will add a Mongoose model to define a Product model for storing the details of each product. This model will be defined in server/models/product.model.js, and the implementation will be similar to other Mongoose model implementations covered in previous chapters, like the Course model defined in Chapter 6Building a Web-Based Classroom Application. 

For MERN Marketplace, we will keep the product schema simple with support for fields such as product name, description, image, category, quantity, price, created at, updated at, and a reference to the shop. The code defining the product fields in the product schema are given in the following list, along with explanations:

  • Product name and description: The name and description fields will be String types, with name as a required field:
name: { 
type: String,
trim: true,
required: 'Name is required'
},
description: {
type: String,
trim: true
},
  • Product imageThe image field will store an image file to be uploaded by the user as data in the MongoDB database:
image: { 
data: Buffer,
contentType: String
},
  • Product categoryThe category value will allow grouping products of the same type together:
category: { 
type: String
},
  • Product quantityThe quantity field will represent the amount available for selling in the shop:
quantity: { 
type: Number,
required: "Quantity is required"
},
  • Product priceThe price field will hold the unit price this product will cost the buyer:
price: { 
type: Number,
required: "Price is required"
},
  • Product shopThe shop field will reference the shop to which the product was added:
shop: {
type: mongoose.Schema.ObjectId,
ref: 'Shop'
}
  • Created and updated at timesThe created and updated fields will be Date types, with created generated when a new product is added, and the updated time changed when the product's details are modified:
updated: Date,
created: {
type: Date,
default: Date.now
},

The fields in this schema definition will enable us to implement the product-related features in MERN Marketplace. To begin the implementation of these features, in the next section, we will implement the full-stack slice that will allow sellers to add new products to their existing shops in the marketplace.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset