Product
Below is the Product server script. In this example we are using mongoose ORM library for database operations. This server script creates and initiates the Product Schema.
```javascript```
const mongoose = ob.mongoose;
const { Schema, model, SchemaTypes } = mongoose;
const { String, Boolean, Date, Number } = SchemaTypes;
const stockSchema = new mongoose.Schema({
price: Number,
quantity: Number
});
const initiate = () => {
const ProductSchema = new Schema({
title: String,
sku: String,
name: {
type: String,
required: [true, "please provide a name for this product"],
trim: true,
lowercase: true,
unique: [true, "name must be unique"],
minLength: [3, "name must be at least 3 character"],
maxLength: [20]
},
description: {
type: String,
required: true
},
category: [
{
type: String
}
],
stock: [stockSchema],
type: String,
last_stock_price: Number,
total_quantity: {
type: Number,
default: function() {
const quantity = this.stock.reduce((acc, value) => {
return (acc += value.quantity);
}, 0);
return quantity;
}
},
unit: String,
created_on: Date,
updated_on: Date,
created_by: String,
updated_by: String,
domain: String
});
try {
// ob.log(mongoose.modelNames());
mongoose.connection.deleteModel("Product");
} catch (e) {}
ProductSchema.pre("save", function(next) {
const doc = this;
ob.log("XXXXXXXXXXXX" + JSON.stringify(doc));
doc.created_on = new Date();
doc.updated_on = new Date();
ob.sequence("om_products", doc.domain, seq => {
doc.sku = seq;
next();
});
});
return model("Product", ProductSchema);
};
module.exports.Product = initiate();
Last updated