mongodb - PyMongo - 名称必须是 Str 的实例

标签 mongodb python-3.x pymongo

我正在尝试从 MongoDB Atlas 上的数据库读取和写入,虽然我可以很好地从我的集合中读取数据,但任何写入集合的尝试都会导致 PyMongo 引发异常“名称必须是 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

最佳答案

在您的“setattributes()”中,您通过名称访问一个 pymongo 集合实例:

collection = db.database[self.tablename]

然后在“insertdata()”中你尝试再次做同样的事情,但现在“collection”不是一个字符串,它是一个 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)

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

关于mongodb - PyMongo - 名称必须是 Str 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46510596/

相关文章:

python-3.x - seaborn 如何设置样式和字体大小

python - 可能金额的功能不会超过一次

python - 如果文档存在,MongoDB 返回 True

python - Pymongo如何更新数组中行的特定值

mongodb - azure 支持 mongodb 和 redis 等吗?

MongoDb:如何对日期字段进行聚合、分组和排序?

java - mongodb 点表示法查找

node.js - 如何在使用 Node js 上传后从后端更改视频 fps/比特率意味着它应该在视频中从 144p 实时更改为 240p

python - kivy 和 python3 在 ubuntu 18.04 上不工作

python - 插入后如何更新 Mongo 文档?