PyMongo - Name必须是Str的一个实例

时间:2017-10-01 08:29:34

标签: mongodb python-3.x pymongo

我正在尝试从MongoDB Atlas上的数据库读取和写入,虽然我可以从我的集合中读取数据,但任何写入集合的尝试都会导致PyMongo引发异常'name必须是str的实例”。

我猜这是对MongoClient对象的引用,但问题是我正在使用连接字符串。任何人都能帮我解决我做错的事吗?

我的代码如下:(我有很多评论可以帮助我更好地理解,所以请原谅我的简洁)

def setattributes(self, rowdict):
        """ a function to create a user. Assumes that only a data
        dict is provided. strips everything else and updates.
         what the data dict contains is your problem.
        """
        with UseDatabase(self.dbconfig) as db:
            collection = db.database[self.tablename]
            locationdict = {    #create a corresponding location entry
            'email' : rowdict['email'],
            'devstate' : 0,
            'location' : {
            'type': 'Point',
            'coordinates' : [ 0, 0 ]
            },
            'lastseen' : datetime.now()
            }
            try:
                res = db.insertdata(collection, rowdict) #insert user data
            except Exception as e:
                print("Error adding user to DB : %s" % e)
                return False  # if you cant insert, return False
            try:  
                loccollection = db.database[self.locationtable]
                resloc = db.insertdata(loccollection, locationdict)
            except Exception as e: # if the status update failed
                db.collection.remove({'email' : rowdict['email']}) 
                #rollback the user insert - atomicity
                return False
        return True

我的数据库代码如下:

class ConnectionError(Exception):
    pass

class CredentialsError(Exception):
    pass

class UseDatabase:
    def __init__(self, config: dict):
        self.config = config

    def __enter__(self, config = atlas_conn_str):
        try:
            self.client = MongoClient(config)
            self.database = self.client['reviv']
            return self

        except:
            print("Check connection settings")
            raise ConnectionError

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.client.close()

    def insertdata(self, collection, data):
        post = data
        post_id = self.database[collection].insert_one(post).inserted_id
        return post_id

    def getdetails(self, collection, emailid):
        user = collection.find_one({'email' : emailid}, {'_id' : 0})
        return user

1 个答案:

答案 0 :(得分:3)

在您的" setattributes()"中,您可以按名称访问pymongo Collection实例:

collection = db.database[self.tablename]

然后在" insertdata()"你试图再次做同样的事情,但现在"集合"不是字符串,它是Collection实例:

post_id = self.database[collection].insert_one(post).inserted_id

相反,只需:

post_id = collection.insert_one(post).inserted_id

顺便说一下,我看到您已经编写了一些代码来确保为每个操作创建和关闭MongoClient。这不必要地复杂化,并且通过为每个操作要求新的连接,它将显着减慢您的应用程序。 As the FAQ says,"为每个进程创建一次此客户端,并将其重用于所有操作。为每个请求创建一个新客户端是一个常见的错误,这是非常低效的。"

我建议您删除UseDatabase类,使MongoClient成为模块全局变量,并直接使用MongoClient:

client = MongoClient(atlas_conn_str)
db = client[locationtable]

class C:
    def setattributes(self, rowdict):
        collection = db[self.tablename]
        # ... make rowdict as usual, and then:
        res = collection.insert_one(rowdict)

此代码更简单,运行速度更快。