so i have this mongodb document (see below) i am updating my mongodb document, with this donateList and requestList. so here's the case: if a user in my webapplication, donating a book. i want to save that books bookid by updating the document. but becouse its updating the document every single time i cant save the previous bookid's. Same gose with requestList case. all i want is save bookid everytime a user donate or request a book.
Code
@app.route('/donate', methods=['GET', 'POST'])
@app.route('/donate books', methods=['GET', 'POST'])
def donate_books():
form = DonateBooks()
if 'email' in session and request.method == 'GET':
return render_template('donate.html', title="Donate Books", form=form)
elif 'email' in session and request.method == 'POST':
if form.validate() == False:
flash('All fields are required !')
return render_template('donate.html', title="Donate books", form=form)
else:
donate = mongo.db.mylogin
Donating_books = donate.insert(
{'bookname': form.bookname.data, 'bookdesc': form.description.data, 'donatedby': session['username']})
flash('Successfully donated !', 'success')
bookId = donate.find_one({"bookname" : form.bookname.data })
final_id = dict(bookId)
new_id = final_id['_id']
inserting_id = donate.update_one({'name' : session['username']}, {'$set': {"donateList": [{"bookid": new_id}], "requestList" : [{"bookid" : new_id}]}})
return render_template('donate.html', title='Donate Books', form=form)
else:
flash('Please Login/Sign Up first to Donate Books !')
return redirect(url_for('home'))
All you need to do is use $addToSet instead of $set
in your update like so:
inserting_id = donate.update_one({'name' : session['username']}, {'$addToSet': {"donateList": {"bookid": new_id}, "requestList" : {"bookid" : new_id}}})