如何在python flask中使用mongodb制作搜索栏?

问题描述 投票:0回答:1

我试着为我的大学项目做一个搜索栏,但我不知道我哪里出错了,它在我的控制台给了我一个错误的405,我不确定,但我认为我在python flask中的搜索命令,我想搜索那些产品是错误的,我很抱歉,如果这个问题困扰你,我是新的python flask和mongo db。

jquery

$(document).ready(function(){
                $("#livebox").on("input",function(e){
                    textinLivebox = $("#livebox").val();
                    console.log(textinLivebox)
                    $.ajax({
                        method:"post",
                        url:"/livesearch",
                        data:{text:textinLivebox},
                        success: function(res){
                            console.log(res)
                        }
                    })
                });
            })

蟒蛇烧瓶

@app.route("/livesearch")
def livesearch():
    searchbox = request.form.get("text")
    data = mongo.db.Product.find({"title"})
    result = Product.objects.all(data)
    return jsonify(result)

我的数据库

class Product(db.Document):
    product_id  = db.IntField( unique=True)
    title       = db.StringField(max_length = 50)
    img_file    = db.StringField(nullable=False, default='static/img/dettol.jpg')
    price       = db.StringField(max_length = 50 )
    description = db.StringField( max_length = 50)
python jquery mongodb flask pymongo
1个回答
0
投票

请按照以下步骤进行操作。

  1. 在文本上创建索引(在Mongo shell中)。

    db.collection.createIndex( { name: "text", description: "text" } )
    
  2. 使用 $text 操作符来进行搜索 (在 Python 代码中)。

    db.collection.find( { '$text': { '$search':  searchbox} } )
    

    你可以阅读更多关于这个 此处.

对于 405 错误,您可以添加 POST 途径中的方法。

@app.route("/livesearch", methods=["POST"])
© www.soinside.com 2019 - 2024. All rights reserved.