PYMONGO:无法从数据库中检索数据

时间:2018-07-31 19:12:21

标签: python mongodb flask pymongo

我正在尝试使用python 3.6.5,pymongo 3.7.1和

建立一个简单的博客。

我能够成功地将博客文章添加到集合中,并且当我运行命令db.posts.find({}).pretty()时,我会得到正确的结果,即posts集合中有两个条目。但是,当我尝试使用下面定义的功能检索由post_id指定的博客帖子时,得到的结果为None

以下是我的database.py文件,在其中初始化数据库并编写插入和检索方法

import pymongo

class Database(object):
     URI = "mongodb://127.0.0.1:27017"
     DATABASE = None

    @staticmethod
    def initialise():
        ## get the client with Database.URI
        client = pymongo.MongoClient(Database.URI)
        ##  get the database that we are using
        Database.DATABASE = client["fullstack"]

    @staticmethod
    def insert(collection, data):
        ## get me the collection in this database and insert some data into it
        Database.DATABASE[collection].insert(data)

    @staticmethod
    def find(collection, query):
       Database.DATABASE[collection].find(query) # returns a cursor.cursor object

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

以下是我的posts.py文件,其中包含具有指定集合名称的插入和检索功能

from database import Database
import uuid
class Post(object):
    def __init__(self, blog_id, title, post_id=None):
        self.content = content
        self.author = author
        self.blogId = blog_id
        self.postId = uuid.uuid4().hex if post_id is None else post_id
        self.date = date

    def save_to_mongo(self):
       Database.insert(collection="posts",
                    data= self.json())
    def json(self):
        return {
        "blogId": self.blogId,
        "postId": self.postId,
        "title": self.title,
        "content": self.content
    }

    @staticmethod
    def from_blog(id):
        return [post for post in Database.find(collection="posts", query={"blogId": id})]

app.py文件,我在其中调用上面定义的功能:

import pymongo
from database import Database
from models.posts import Post

Database.initialise()
post1 = Post(
    blog_id = "123",
    title = "blog title",
    content = "sample content",
    author = "Jose"
)

post1.save_to_mongo()    # successfully add posts
post = Post.from_mongo('7338d2ab285e4073b81e57afbad416f2')
print(post) # returns none, but there is an entry with that postId
print(Database.DATABASE["posts"].find({"blogId": "123"})) # returns desired result i.e a cursor.curso object
print(Database.DATABASE["posts"].find_one({"postId": "7338d2ab285e4073b81e57afbad416f2"})) # returns desired result, the item with the postId specified

我在这里做什么错了?

0 个答案:

没有答案
相关问题