0
votes

I'm doing a simple recipe project using Python, Pymongo and Flask. I have an existing recipe collection in MongoDB. I have it coded so that I can view those recipes individually and click a button which will save the recipe to my saved_recipe collection. If I view the same recipe and go to save it again, I obviously get the "E11000 duplicate key error" as the _id(ObjectId) already exists in the collection (see image below).

enter image description here

I'd love to either have a popup on the same screen telling the user they have already added that recipe to their Saved Recipe folder or simply redirect them by rendering a template explaining they already have that recipe, something to that effect.

Is this possible?

I'm thinking something along the lines:

if ObjectId == ObjectId
    return render_template('error.html')

Here is my code to help explain:

recipe_id = recipes.find_one({"_id": ObjectId(recipe_id)})
    savedrecipe.insert_one(recipe_id)
    if 'username' in session:
        return redirect(url_for('saved_recipes'))
    return redirect(url_for('login'))

So, I'm finding a particular _id in a collection in my database. I'm then inserting that found id into a different collection. If I try to add the same id into the same collection I get the "duplicate error". Is there a way to maybe find the id as I have above, then insert it into the collection I want but create a new id for it?

1

1 Answers

2
votes

You can use a try/except block when saving the recipe. Something like this:

try:
    recipe.save()
except DuplicateKeyError:
    return render_template('error.html')

Obviously this leaves out a lot of details, but that's the general idea.