0

The code to get couponId from document:

 function getLatestCouponId() {
 var cursor = db.collection('Coupon').find().limit(1).sort({ $natural : -1 });
 cursor.count(function(error, nbDocs) { 
    if (error) throw error;
    if(nbDocs == 0){
       couponId=1;
       insertData();
    }
    else if(nbDocs==1){
       cursor.toArray(function(err, docs) {
            if (err) throw err;
                console.log('%j', docs);
                couponId = docs[0].couponId;
                
       });
                    
      insertData();
    }
  });
}

The above code tries to find the latest document in the collection coupon and find its coupon id column but unfortunately coupon id is returning null console.log prints log as:

  [{"_id":"5a819ae4ee37582288837c9f","couponId":90,"district":"Thiruvananthapuram","taluk":"Thiruvananthapuram","landmark":"SCTIMST"}]

The code showing how I inserted docs into the collection is given below:

function insertData(){
    console.log("No of Coupons" + totalCoupon);
        //var newLandMark = { "hotelName": hotelName, "district": district, "taluk": taluk, "landmark":landmark,  "dateCreation": new Date(), 
    //};
    for(i=0;i<totalCoupon;i++){
    

        var doc ={"couponId":couponId, "district":district, "taluk":taluk, "landmark":landmark};
        docs.push(doc);
        couponId=couponId+1;;
    }
        db.collection('Coupon').insertMany(docs, {w: 1}, function(err, records){
            var itemsProcessed = 0;
            if (err) throw err;
            else{
                rdata["status"] = "ok";
                callback();

            } 
    
        });
        }

doc which was logged

log from terminal

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
adarsh dev
  • 31
  • 6

0 Answers0