如果在数据实际存储在数据库之前多次调用 insert_one() ,如何阻止 pymongo MongoDb 添加重复数据?
我正在向 MongoDb 注册用户(姓名、电子邮件、密码),首先检查该电子邮件是否已被注册过。
def find_by_email(email: str):
return Database.find_one("users", {"email": email})
def is_email_used(email: str):
if User.find_by_email(email) is None:
return True
else:
return False
如果 find_by_email() 没有注册或找到电子邮件,则站点将继续将数据添加到数据库。
def register_user(email, password, name):
new_user = User(email, password, name)
new_user.create_words()
Database.insert(new_user.collection, new_user.json())
@staticmethod
def insert(collection: str, data: Dict):
Database.DATABASE[collection].insert_one(data)
如果用户在将数据插入数据库之前再次单击“提交”,则会出现问题,整个函数将再次运行,并且由于尚未上传数据,因此 find_by_email() 返回 None 并允许用户注册两次。
本质上,在将初始提交插入数据库之前,可以通过多次单击“提交”来创建尽可能多的重复项。
我曾考虑过使用“upsert=True”,但没有解决根本问题。正在考虑“等待”以确保在继续之前上传数据,但太菜鸟无法真正理解异步。
如何确保数据先插入再继续?
I am registering users (name, email, password) to MongoDb and first check to see if the email has been registered before.
def find_by_email(email: str):
return Database.find_one("users", {"email": email})
def is_email_used(email: str):
if User.find_by_email(email) is None:
return True
else:
return False
If no email is registered or found by find_by_email() the site goes onto to add the data to the DB.
def register_user(email, password, name):
new_user = User(email, password, name)
new_user.create_words()
Database.insert(new_user.collection, new_user.json())
@staticmethod
def insert(collection: str, data: Dict):
Database.DATABASE[collection].insert_one(data)
The problem arises if the user clicks submit again before the data is inserted to the DB the whole function is run again and since no data has been uploaded yet the find_by_email() returns None and allows for the user to register twice.
Essentially as many duplicates can be created by clicking submit multiple times before the initial submit is inserted to the DB.
I had thought about using "upsert=True "but nor addressing the root problem. Was thinking about "await" to ensure data is uploaded before continuing but too much of a noob to really understand async.
How to ensure the data is inserted first before continuing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论