【问题标题】:PyMongo returns None even when the db shows the data即使数据库显示数据,PyMongo 也返回 None
【发布时间】:2018-02-04 13:31:21
【问题描述】:

我正在尝试制作一个简单的博客,其中我正在尝试从数据库中插入和获取数据。插入数据工作正常,但使用.find().find_one() 获取数据返回None,即使在shell 中执行相同的语句也有效。

我正在尝试使用以下一系列代码跨三个文件获取数据

数据库.py

@staticmethod
def fetchdata(collection):
    Database.DATABASE[collection].find_one()

post.py

@staticmethod
def fetch_from_db():
    return Database.fetchdata('posts')

app.py

Database.initalise()
testPost = Post.fetch_from_db()
print(testPost)

【问题讨论】:

  • 你没有从 fetchdata 返回任何东西
  • 你把find_one()返回的文件扔掉了。您需要像这样返回它:return Database.DATABASE[collection].find_one()
  • @S.M.Styvane 谢谢。我的代码现在可以工作了!
  • @user602525 谢谢,它有帮助。

标签: python mongodb pymongo


【解决方案1】:

您缺少 fetchdata 函数中的 return 语句。应该是这样的

@staticmethod
def fetchdata(collection):
    return Database.DATABASE[collection].find_one()

因为它没有返回任何东西,fetch_from_db 没有得到任何数据,因此将None 作为输出。

【讨论】:

    【解决方案2】:

    这是一个有据可查的问题,示例代码:

    >>> from pymongo import MongoClient
    >>> c = MongoClient()
    >>> c.test_db.test_col.find_one()
    {u'test': u'document', u'x': 1, u'_id': ObjectId('5980a8fd168186e9fb46c638'), u'other': u'value'}
    

    编辑:

    如果你愿意,也可以这样写:

    >>> c = MongoClient()
    >>> db = c.test_db
    >>> col = db.test_col
    >>> col.find_one()
    {u'test': u'document', u'x': 1, u'_id': ObjectId('5980a8fd168186e9fb46c638'), u'other': u'value'}
    

    documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      • 2019-04-20
      • 2022-10-20
      • 1970-01-01
      相关资源
      最近更新 更多