How to Make Discount coupon codes in NodeJs & MongoDb
Pouya Jabbarisani

Your code doesn’t work, try it with this simple script on the command line first:

const process = require(“process”);

const mongoose = require(“mongoose”);

const Schema = mongoose.Schema;

var Coupon = mongoose.model(


new Schema({

code: {

type: String,

required: true,

unique: true






{ useNewUrlParser: true, useCreateIndex: true }


function coupongenerator() {

return “ABC123”;

/*var coupon = “”;

var possible = “abcdefghijklmnopqrstuvwxyz0123456789”;

for (var i = 0; i < 3; i++) {

coupon += possible.charAt(Math.floor(Math.random() * possible.length));


return coupon;*/


let isExistDiscount = false;

do {

let myDiscountCode = coupongenerator();

let newCoupon = new Coupon({

code: myDiscountCode


console.log(`Saving coupon with code ${myDiscountCode}`);



.then(coupon => {




.catch(error => {

console.log(‘Duplicate code’, error);

isExistDiscount = true;



} while (isExistDiscount);

If you run this multiple times you would expect the script to generate multiple coupons but it fails and just prints out the error. The only way to generate a truely unique code is to get all the codes in the table into an array, generate the coupon code and then check against the array till you get a code that’s truely unique. The save function has a callback (or pomise whatever you prefer) so it gets called after the do-while loop has already ended.