我創建了一個電報機器人,它將所有啟動該機器人的人保存到 pymongo 資料庫中。我有這個問題:如果用戶再次點擊開始,會出現錯誤:pymongo.errors.DuplicateKeyError: [...]
如何處理?
import motor.motor_asyncio
from datetime import datetime
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
TOKEN = ''
cluster = motor.motor_asyncio.AsyncIOMotorClient('')
collection = cluster.Dimalexus.BOT
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
def add_user(user_id, user_name, name):
date = datetime.now().date()
collection.insert_one({
'_id' : user_id,
'name' : name,
"username" : user_name,
"date" : str(date)
})
@dp.message_handler(commands=['start'])
async def welcome_send_info(message: types.Message):
await message.reply('привет')
name = message.from_user.full_name
user_name = message.from_user.username
user_id = message.from_user.id
try:
add_user(user_id, user_name, name)
except Exception as e:
print(e)
if __name__ == "__main__":
executor.start_polling(dp, skip_updates=True)
嘗試 - 除了不作業
uj5u.com熱心網友回復:
這是因為您嘗試插入該檔案中已經存在的值而發生的重復錯誤。
要處理這個問題,您可以嘗試使用另一個函式而不是insert_one():
update_one()。這個通常用于更新已經存在的記錄,但是upsert = True如果沒有找到具有該過濾器的檔案,您可以使用該引數插入新的記錄。
正如這里所說,該函式主要接受兩個引數和其他可選的:
filter:這個是用來查找要更新的記錄的;new_values:更新的值;upsert:這是您需要的引數。
您將需要的代碼是:
def add_user(user_id, user_name, name):
date = datetime.now().date()
collection.update_one({
"_id" : user_id
}, {
'_id' : user_id,
'name' : name,
"username" : user_name,
"date" : str(date)
}, upsert = True)
有了這個,您將搜索該 ID。如果沒有找到,它會創建一個新記錄,否則你可以使用已經設定的記錄:)
uj5u.com熱心網友回復:
_id是唯一的id,不能加倍數。通過 upsert 使用更新:
collection.update_one(
{
"_id" : user_id
},
{
'_id' : user_id,
'name' : name,
"username" : user_name,
"date" : str(date)
}, upsert=True)
或者你可以在資料庫中搜索_id,如果已經存在,則不添加。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/495732.html
上一篇:Node.js/MongoDB-TypeError:無法解構'req.body'的屬性'title',因為它未定義
下一篇:出現錯誤:querySrvECONNREFUSED_mongodb._tcp.auctiondbcluster.s6rzg.mongodb.net。當我離線時嘗試連接到localhost
