ฉันกำลังพยายามอ่านและเขียนจากฐานข้อมูลบน 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