javascript - 自动篮子清洁和数量更新 - 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);
}
});
解决方案
当用户以这种方式将它们添加到购物车时,为什么要从数据库中减少数量假设产品有 2 个数量并且用户将它们添加到购物车并且从未购买,但是 10 分钟后用户来到您的应用程序并且他真的想购买该产品但是他不能,因为该产品在 App 上不可用,但在商店有售。因此,为了克服这个问题,您应该在客户端处理用户不能添加超过可用数量的问题,当用户按下保存按钮保存在购物车中然后将该记录添加到数据库中,当用户转到付款页面时,您应检查可用数量是否足以满足用户的购物车要求,如果是,则在成功交易后抢购付款,从产品真实记录中减少产品数量。
推荐阅读
- python - 使用 django-channels/websocket 更新实时位置的有效方法
- java - 为什么不在 Android 上的 Activity 中调用 onActivityResult
- css - 自定义 css 重新排列移动尺寸屏幕中的标题位置
- kendo-ui - 如何在两个形状之间动态建立连接,意味着位置和所有将在剑道图中动态传递
- javascript - 本地存储不适用于记住类切换的最后用户输入
- python - 无法将 feed_dict 键解释为 Tensor:Tensor Tensor("Placeholder:0", shape=(135162, 6), dtype=float32) is not an element of this graph
- typescript - 运行一个将 typescript 测试与 jest 合并的声明
- javascript - 对检测功能存在的“hasOwnProperty”感到困惑
- c# - 如何在 html 中将字符串转换为 html
- php - 如何在保留兄弟键值对的同时基于键值与数组相交