How to Make Discount coupon codes in NodeJs & MongoDb

Pouya Jabbari Sani
Pouya Jabbari Sani’s Blog
2 min readJun 15, 2018

--

Maybe you would like to build a discount system for your online store or platform. In the first look, It seems a little scary and complicated, but it’s so easy in NodeJs/MongoDB based systems!
First of all, You need to add a discount model to your model’s folder in your product ready nodeJs project:

var mongoose = require(‘mongoose’);var connection = mongoose.createConnection(“mongodb://localhost/{customName}”);var DiscountCodesSchema = mongoose.Schema({code: { type: String, require: true, unique: true },isPercent: { type: Boolean, require: true, default: true },amount: { type: Number, required: true } // if is percent, then number must be ≤ 100, else it’s amount of discountexpireDate: { type: String, require: true, default: ‘’ },isActive: { type: Boolean, require: true, default: true }});DiscountCodesSchema.pre(‘save’, function (next) {var currentDate = new Date();this.updated_at = currentDate;if (!this.created_at) {this.created_at = currentDate;}next();});var Discounts = mongoose.model(‘DiscountCodes’, DiscountCodesSchema);module.exports = Discounts;

Then, you need to make a random code generator for making discount coupon codes, For this step, I prefer to make a separate module and save my function in it:

function coupongenerator() {var coupon = “”;var possible = “abcdefghijklmnopqrstuvwxyz0123456789”;for (var i = 0; i < {custom code length in here}; i++) {coupon += possible.charAt(Math.floor(Math.random() * possible.length));}return coupon;}module.exports = coupongenerator;

Then, We can easily use it in our API route. BUT before than saving generated code, you need to check if code is existing, Make a new one:

let isExistDiscount = falsedo {let myDiscountCode = coupongenerator()let newDiscountCode = new DiscountCode({code: myDiscountCode,isPercent: false,amount: [{ IRT: 5000 }, { USD: 5 }, { EUR: 5 }],expireDate: ‘’,isActive: true})newDiscountCode.save(function (err) {if (err) {if (err.name === ‘MongoError’ && err.code === 11000) {// Duplicate code detectedisExistDiscount = true;}}res.send({//success message render})})}while (isExistDiscount);

And finally, you can use the discount coupon code field in anywhere check and process it from MongoDB.

Good luck!

By the way, I’m looking for a visa-sponsored job in the UK. If you are looking someone like me to hire, send me a message.

--

--