首页 > 解决方案 > 自动篮子清洁和数量更新 - Mongoose、Mongodb、Nodejs

问题描述

当用户将产品添加到购物车时,我会减少数据库中的产品数量。半小时后,我希望系统再次检查购物车并自动恢复数量并从购物车中删除产品。

我编写的代码完成了这个过程,但我怎样才能让它更健康呢?你有什么建议?我应该使用哪种方法?

篮子保存在数据库和用户中的部分

var task = cron.schedule('30 * * * *', async () => { // 30 minutes
            try{
                var userid = await req.user._id;
                var user = await User.findById(userid); //I find the user
                var items = user.cart.items;  //I find the user's cart
                var product_id = await Product.find({}, '_id'); // I called all the products

                if(items.length){ //If there is a product in the user's cart, come in
                    for(var i=0; i<items.length; i++){ 
                        for(var j=0; j<product_id.length; j++){
                            
                            var item = items[i]; //I find first product and second and... in the cart
                            var result = items[i].quantity; // I find its quantity

                            if(item.productId.toString() == product_id[j]._id.toString()){
                                var product = await Product.findById(item.productId).exec();
                                var productQuantity = product.productQuantity; // Find product quantity
                                var productQuantityResult = productQuantity + Number(result); // and restore stock

                                product.productQuantity = productQuantityResult; 

                                await product.save(); //Save the new quantity
                                await req.user.deleteCartItem(product_id[j]._id ); //delete the product from the cart
                                continue;
                            }
                        }
                    }    
                }else{ // If there is a no product in the cart, come in
                    console.log("cart is empty!");
                    task.stop(); // stop the loop
                }
            }
            catch(err){
                next(err);
            } 
        });

标签: javascriptnode.jsmongodbmongoose

解决方案


当用户以这种方式将它们添加到购物车时,为什么要从数据库中减少数量假设产品有 2 个数量并且用户将它们添加到购物车并且从未购买,但是 10 分钟后用户来到您的应用程序并且他真的想购买该产品但是他不能,因为该产品在 App 上不可用,但在商店有售。因此,为了克服这个问题,您应该在客户端处理用户不能添加超过可用数量的问题,当用户按下保存按钮保存在购物车中然后将该记录添加到数据库中,当用户转到付款页面时,您应检查可用数量是否足以满足用户的购物车要求,如果是,则在成功交易后抢购付款,从产品真实记录中减少产品数量。


推荐阅读