I'm making an online business jargon dictionary using MongoDB. I want to make it possible to vote terms up and down. I'm getting to grips with CRUD, but I'm a bit stumped on the syntax for updating part of a record.
I have this template:
<div >
<a href="{{url_for('like', entry_id=entry._id)}}">
<i ></i></a>
</div>
The logic is that when "like" is clicked, the code should pull "love_percent"
from a dictionary, convert to integer (or provide value zero if not present), add 1, convert to string and update within the same ObjectID
. This is the code I wrote for that route:
@app.route("/like/<entry_id>")
def like(entry_id):
entry = mongo.db.jargon.find_one({"_id": ObjectId(entry_id)})
value = int(entry["love_percent"][0])
value = 1
value = str(value)
entry.update_one({"_id": ObjectId(entry_id)},
{"$set": {
love_percent[0]: value
}})
return render_template("jargon.html")
I tried using just update or storing the integer but that seemed to fix it. A friend suggested update_one
but I'm basically a bit confused and lost.
Can anyone suggest what I'm missing here or a better approach?
(I'm aware that this doesn't prevent multiple votes from the same user; that functionality can come later.)
The dictionary is being staged on Heroku here and I have pushed it through with the bug: http://jargon-unchained.herokuapp.com/get_jargon
I get the following Error on Traceback: AttributeError: 'dict' object has no attribute 'update_one'
The repository for this code is in Github: https://github.com/dandavies23/jargon-unchained
CodePudding user response:
As per my understanding of the question.
You need to change the following:
- As you have only like an option right now
value = int(entry["love_percent"])
- You are changing in the database, so use the following command.
mongo.db.jargon.update_one({"_id": ObjectId(entry_id)},
{"$set": {
"love_percent" : value
}})
Do try and tell issues faced in the comments.
CodePudding user response:
Removed [0] which I thought wasn't a position but a default integer. Resolved issue giving each entry a default of 55 on data-entry.
I was also re-rendering the template with a term I hadn't defined within the function. Fixed with a redirect.
def like(entry_id):
entry = mongo.db.jargon.find_one({"_id": ObjectId(entry_id)})
value = int(entry["love_percent"])
value = 1
value = str(value)
mongo.db.jargon.update_one({"_id": ObjectId(entry_id)},
{"$set": {
"love_percent": value
}})
return redirect(url_for("get_jargon"))