如何使用 html 中的按钮更新 mongodb,pymongo

how to update mongodb using button in html, pymongo

我有一个 base.html,其中包含项目和供用户单击的按钮。

                                <p class="card-text">{{data[0].name}}</p>
                                <div class="d-flex justify-content-between align-items-center">
                                <div class="btn-group">
                                    <form action="/update/<%= data[0]._id %>" method="PATCH">
                                    <p style="margin-right:5px;">Available: {{data[0].inventory}}</p>
                                    <button type="button" class="btn btn-sm btn-outline-secondary">Add to cart</button>
                                    </form>
                                </div>

我有 hello.py python 运行服务器的文件。

from flask import Flask, render_template, redirect, request, url_for
from pymongo import MongoClient
from bson.objectid import ObjectId
app = Flask(__name__)
 

@app.route('/',methods=['GET'])
def mongoTest():
    client = MongoClient('mongodb://localhost:27017/')
    db = client.ecommerce
    collection = db.items
    results = collection.find()
    # client.close()
    return render_template('base.html', data=results)


@app.route("/update/:id", methods=["PATCH"])
def update_inventory(id):    
    client = MongoClient('mongodb://localhost:27017/')
    db = client.ecommerce
    id=request.values.get("_id")    
    db.items.update_one({ '_id': id}, {'$inc': {'inventory': -1}}, upsert=False)
    results2 = db.items.find()
    return render_template('base.html', data=results2)

if __name__ == '__main__':
    app.run(debug=True)

但是,它不会更新库存值。 我该如何解决这个问题?

id是字符串吗?如果是这样,则需要将其转换为 ObjectId。 (在大多数情况下,您让 mongo 处理 ID,因此 ID 是 ObjectId,而不是字符串)。

from bson.objectid import ObjectId

@app.route("/update/:id", methods=["PATCH"])
def update_inventory(id):    
    client = MongoClient('mongodb://localhost:27017/')
    db = client.ecommerce
    id = ObjectId(request.values.get("_id"))
    db.items.update_one({ '_id': id}, {'$inc': {'inventory': -1}}, upsert=False)
    results2 = db.items.find()
    return render_template('base.html', data=results2)

否则,您必须检查:

  • 如果 id 存在,如果不存在 return 错误?
  • “项目”collection 是否存在? (不是项目也不是项目?)