Luca_54
Luca_54

Reputation: 539

MongoDB: Update function does not return a response in Python Flask

I built a small script in Flask that takes a file from my MongoDB with the vkey and updates the credits and level from the document:

        client = pymongo.MongoClient("mongodb+srv://root:<password>@cluster0.3ypph.mongodb.net/data?retryWrites=true&w=majority")
        db=client["data"]
        col=db["user_currency"]
        h=hmac.new(b"test",b"",hashlib.sha3_512)
        credits_update=credits-cost
        h.update(vkey.encode("utf8"))
        try:
            db.col.update_one(
                {"vkey":h.hexdigest()},
                {"$set":{"credits":str(credits_update)}}
            )
            db.col.update_one(
                {"vkey":h.hexdigest()},
                {
                    "$set":{"level":count},
                    "$currentDate": { "lastModified": True }
                }
            )
        except:
            return redirect("/currency?error=02")
        else:
            return redirect("/currency?bought=lvlboost")

However, nothing is updated in MongoDB after execution and it only returns to the target page /currency?bought=lvlboost. I reloaded the database and also checked the vkey for correctness. Both are identical. Does anyone know what the problem could be?

Upvotes: 1

Views: 501

Answers (1)

NavaneethaKrishnan
NavaneethaKrishnan

Reputation: 1318

Add a variable to your query, so that the return value will be added to that,

result = db.col.update_one(
    {"vkey":h.hexdigest()},
    {
        "$set":{ "level":count, "credits":str(credits_update) },
        "$currentDate": {"lastModified": True } 
    }
)

Now if you print(result) you can see the matched_count and the modified_count.

Doc: https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/#returns

Upvotes: 1

Related Questions