0

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.

enter image description here

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'))
1
  • can you use share collection at jsoneditor at online? Commented Dec 25, 2019 at 7:38

1 Answer 1

1

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}}})
Sign up to request clarification or add additional context in comments.

2 Comments

i am gonna try that, i am preety new to mongodb.
@ tom slabbaert, whoa, this $addToSet method worked ! Accepted you answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.