Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching Collections and saving in Flask-Mongoengine

I am having trouble saving documents to a new collection and then deleting them from the old one. I create a new object like so:

class Test(mongo.Document):
     field = mongo.StringField()

t = Test(field="test")
t.switch_collection('default')
t.save()
t.switch_collection('switched')
t.save()
t.switch_collection('default')
t.delete()

It seems only to perform the first save to the default collection and then performs nothing after that. I have played around with a bunch of difference options such as reloading the object after every switch/save and from mongoengine context managers:

with switch_collection(Test, 'mongoswitch') as test:
    test(field="switch").save()

My mongo settings look like (called first):

 app.config["MONGODB_SETTINGS"] = {'db': 'TestDB'}
 mongo = MongoEngine(app)

Using mongoengine 0.10 and pymongo 2.8.1 with Python 3.4 .

Anyone have an idea? Much Thanks.

like image 221
austin_ce Avatar asked Jul 15 '15 05:07

austin_ce


1 Answers

I see it's old question but maybe there's someone with the same problem.. I think it's because when you have a document that has id set, by calling t.save() you only update existing document in the collection. To really save it you need to call t.save(force_insert=True)

like image 198
jiripi Avatar answered Oct 20 '22 13:10

jiripi