#354·tinydb

Move a document from a certain database to another one error

Author: AlgoQCreated Nov 23, 2020Updated Nov 24, 2020
Labelspinned

I'm trying to move a document to another database but when I do this twice I get this error:

AssertionError: doc_id 1 already exists

This is probably because I insert the document in the 2th database and then remove it from the first database. This causes that the second document that I insert into database 2 also has document id 1. Is there any workaround for this struggle?

My first python file:

python
from tinydb import TinyDB, Query

db = TinyDB('db1.json')
db2 = TinyDB('db2.json')

def moveDocumentToDb2(id):
    db1 = TinyDB('db1.json')
    db2 = TinyDB('db2.json')

    q = Query()

    document = db.search(q.id == id)[0]

    db2.insert(document)

    db1.remove(q.id == id)

# Inserted document to the first database and it gets the doc_id 1
db.insert({'id': 1, 'type': 'apple', 'count': 7})

# Move the 'apple' document to db2
moveDocumentToDb2(1)

My second python file:

python
from tinydb import TinyDB, Query

db = TinyDB('db1.json')
db2 = TinyDB('db2.json')

def moveDocumentToDb2(id):
    db1 = TinyDB('db1.json')
    db2 = TinyDB('db2.json')

    q = Query()

    document = db.search(q.id == id)[0]

    db2.insert(document)

    db1.remove(q.id == id)

# This document will also get the doc_id 1 (this is the issue)
db.insert({'id': 2, 'type': 'peach', 'count': 3}) 

# Now when I try to add the 'peach' document to db2 I get the error 
# because they both have the same doc_id
moveDocumentToDb2(2)