0
exports.addToCart = async(req,res)=>{
    
      
   
   const cart = await schema.cart.findOne({username:req.body.username})
   
   if(cart){
    return res.status(404).json({
        message:"User's cart is already available, append to the same cart"
    })
   }
   else{
    
    const cart = new schema.cart({
        cartId : getValueForNextSequence("item_id"),
        username : req.body.username,
        productsInCart :req.body.productsInCart

        
    });
    console.log(cart.cartId);
    
    await cart.save();
    res.status(200).json(cart)
   
    }
}

async function getValueForNextSequence(sequenceOfName){
    const sequenceDoc =  await schema.counter.findOneAndUpdate(
       {"_id": sequenceOfName },
       {"$inc":{"sequence_value":1}},
       );
    return sequenceDoc.sequence_value;
   }

THis is the schema for counter I added a document with _id as item_id and sequence_value as 0

const counterSch = new mongoose.Schema({
  _id :{
    type : String
  },
  sequence_value:{
    type : Number
  }
})

getValueForNextSequence method is not returning any value I dont know why please help with this issue.Here I have to increment the cartId automatically but its not happening

James Westgate
  • 11,306
  • 8
  • 61
  • 68

0 Answers0