Reputation: 55
what I'm trying to do is to update a MongoDB document with python and discord.py, but the code i've put doesn't work.
elif string2 == "add":
if string3 == "administrator":
cur = coll.find({"_id" : string1.id})
for doc in cur:
if doc["perm"] == "administrator":
await self.bot.say("Permission {} already found on db for user {}".format(string3, string1.name))
else:
db.users.update_one({"_id" : string1.id, "name" : string1.name, "perm" : "administrator"}, upsert=False)
await self.bot.say("Permissions updated on db for user {}".format(string1.name))
The following is the error.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: update_one() missing 1 required positional argument: 'update'
Document from users collection:
_id: "191598787410526208"
name: "Stevyb0t"
perm: "administrator"
Upvotes: 2
Views: 4163
Reputation: 18201
If your id is a string, you may need to convert it to an ObjectId. Also, you can print the result of the update, and check success:
from bson import ObjectId
result = db.users.update_one(
{"_id": ObjectId(string1.id)},
{"$set":
{"name": string1.name,
"perm": "administrator"}
})
logger.debug('update result: {}'.format(result.raw_result))
if result.matched_count > 0:
# Success code goes here
pass
else:
# Failure code goes here
pass
Upvotes: 2
Reputation: 546
Essentially what other people have commented but with some formatting to make it more legible:
db.users.update_one(
{"_id": string1.id},
{"$set":
{"name": string1.name,
"perm": "administrator"
}})
I also removed upsert=False
since that's the default value anyway so you don't need to specify it - though of course being explicit can be helpful
Edit: read all the comments, suggestion was already made to make accepted comment an answer so here it is. My answer is no different from that comment
Upvotes: 2