Switching Collections and saving in Flask-Mongoengine
Asked Answered
G

2

6

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.

Gushy answered 15/7, 2015 at 5:33 Comment(0)
J
1

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)

Jacktar answered 5/11, 2019 at 10:42 Comment(0)
L
0

Are you getting any errors? It had worked for me. Check records in your mongo db collections.

One possible reason from mongoengine docs:

"Make sure any aliases have been registered with register_connection() or connect() before using the context manager."

Lusitania answered 17/7, 2015 at 10:56 Comment(1)
No I am not getting any errors, I believe it is a problem with mongoengine 0.10, as I just downgraded to 0.09 and they save correctly. Querying that collection is a different story though..Gushy

© 2022 - 2025 — McMap. All rights reserved.