node.js - Saving randomly generated discount coupons into Mongodb using NodeJS -


i have schema coupon , product. trying when product added using api, unit of unique coupons created , inserted coupon , references of coupons should inserted inside product. using coupon-code package generate coupon.

let couponschema = new schema({   code: {type: string, unique: true},   status: {type:boolean, default: false} });  module.exports = mongoose.model('coupon', couponschema);  let productschema = new schema({   prductname: {type: string},   unit: {type: number},   coupon: [{type: schema.types.objectid, ref: coupon}],   category: {type: string} });  module.exports = mongoose.model('product', productschema); 

this post api add product. able save codes coupon collection confused on how save added coupon references product.

api.post('/add', (req, res, next) => {   let newproduct = new product();    newproduct.productname = req.body.productname;   newproduct.unit = req.body.unit;   newproduct.category = req.body.category;    var i;   for(i=0; i<=req.body.unit; i++){     var code = ucg.generate(); // ucg imported coupon-code package     let newcoupon = new coupon();     newcoupon.code = code;     newcoupon.save(err => {       if (err) {         console.log("error occured");         return;       }     });   }    newproduct.save(err => {     if (err) {       res.send(err);       return;     }     res.json({message: "product added successfully."});   }); }); 

can me find out way this? let me know if explanation not enough.

i solved adding push method newproduct.coupon.push(newcoupon.id);

for(i=0; i<=req.body.unit; i++){     var code = ucg.generate(); // ucg imported coupon-code package     let newcoupon = new coupon();     newcoupon.code = code;     newcoupon.save(err => {       if (err) {         console.log("error occured");         return;       }     });     newproduct.coupon.push(newcoupon.id);   } 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -