jeudi 6 septembre 2018

trying to update my MongoDB collection via Python (PyMongo) but my logic is wrong

I'm new to programming and I've been learning Flask for about a week now trying to design an e-commerce website. I have a collection called users, in which each entry looks like this { "_id" : ObjectId("5b9170f1c5eb754e3ab8917f"), "username" : "suhas", "password" : "suhas", "email" : "suhas", "account_type" : "buyer", "cart" : [ { "product_id" : "5b915dd3c5eb754278e160e7", "quantity" : 7 }, { "product_id" : "5b915e3fc5eb754278e160e8", "quantity" : 3 } ] } and a users.products collection, one of the elements look like this

{
"_id" : ObjectId("5b915f02c5eb7544108a14b9"),
"product name" : "Laptop",
"price" : 50000,
"description" : "HP laptop",
"user_id" : "5b914fc3c5eb753eaf81770c",
"username" : "chiranth"

}

I wanted to add a feaure "add to cart" that adds the product_id and quantity into a cart(type list) as dictionaries, as seen in the db.users collection.

The code in Python I've written as:

cart_dict = user_info.get("cart")    

for dict1 in cart_dict:
        for dict1 in cart_dict:
        if dict1["product_id"]==product_id:

            db["users"].update({"_id" : ObjectId(user_id),"cart.product_id":product_id},{ '$inc':{ 'cart.$.quantity':quantity}})
            break
       else:

        db["users"].update({"_id":ObjectId(user_id)},{"$addToSet":{"cart":{"$each":[{"product_id":product_id,"quantity":quantity}]}}})

the problem is,however, that if I increment the second product by adding 2 more to the cart adding to the present 3, the if condition checks the first product, sees that product ID doesn't match and just adds it as a new product AND THEN moves to product 2.

So my question would be how do I ask the if condition to check all product_id's first AND THEN, if none match, add the product?

Sorry for the long, mangled question! I'm a newbie and this my first Q here!

Thanks!!!

Aucun commentaire:

Enregistrer un commentaire