首页 > 解决方案 > 在 MongoDB 中检索项目时在 Flask 中查看错误

问题描述

我正在尝试从 MongoDB 中的项目填充在 Flask 中构建的页面。我的路线看起来像:

@app.route('/job/<posting>', methods=["GET"])
def job_post(posting):
    posting = db.openings.find({'Id': posting})
    title = db.openings.find_one({'Id': posting}, {'Title': 1, '_id':0})
    return render_template('post_page.html', posting=posting, title=title)

我的 post_page.html 模板页面是:

{% extends "layout.html" %}
{% block content%}

<div class="container">


  <article class="media content-section">
    <div class="media-body">
      <div class="article-metadata">
        <h3><a class="mr-2" href="#">{{ title }}</a></h3>
    </div> -->
  </article>


</div>

{% endblock content %}

当我尝试访问一个页面时,我收到一条错误消息"bson.errors.InvalidDocument: cannot encode object: <pymongo.cursor.Cursor object at 0x10dd402e8>, of type: <class 'pymongo.cursor.Cursor'>"

当我研究该错误时,大多数问题都来自使用find而不是find_one. 我在find_one这里使用,当我在 Python shell 中测试它时,title 的变量类型是字典,所以我很困惑为什么它将光标对象传递给模板。

标签: mongodbflaskpymongo

解决方案


您正在传递posting给函数,然后立即在第一个函数中设置它posting = db.openings.find({'Id': posting})。我怀疑你不是故意的。

find()返回一个游标,然后将其传递给find_one()导致您看到的错误的函数。

不知道你想通过调用find()thenfind_one()在同一个集合上来实现什么。我的建议是你删除线posting = db.openings.find({'Id': posting})


推荐阅读