【问题标题】:MongoDB: Update function does not return a response in Python FlaskMongoDB:更新函数在 Python Flask 中不返回响应
【发布时间】:2021-04-10 04:27:28
【问题描述】:

我在 Flask 中构建了一个小脚本,它从我的 MongoDB 中获取一个带有 vkey 的文件,并更新文档中的学分和级别:

        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")

但是,执行后MongoDB中没有任何更新,它只返回到目标页面/currency?bought=lvlboost。我重新加载了数据库并检查了 vkey 的正确性。两者是相同的。有谁知道可能是什么问题?

【问题讨论】:

  • 首先获取每个update_one的返回值;检查matched_countmodified_count 看看是否有任何更新发生。
  • 这些计数的结果是什么?

标签: python mongodb flask pymongo


【解决方案1】:

在查询中添加一个变量,以便将返回值添加到该变量中,

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

现在如果您print(result),您可以看到matched_countmodified_count

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

【讨论】:

  • 谢谢,我现在有数了。两者都为 0。抱歉,我无法直接找到。我对这个主题还比较陌生。
  • 如果matched_count = 0,则没有与您的查询匹配的条目。检查您的查询"vkey":h.hexdigest()
  • 我也认为可能是因为这个。但我也测试了一种选择方法并且它有效。打印时 vkey 与数据库中的匹配。
猜你喜欢
  • 2020-09-08
  • 2014-01-10
  • 1970-01-01
  • 2019-04-05
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多