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.

austin_ce
  • 1,063
  • 15
  • 28

2 Answers2

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)

jiripi
  • 656
  • 1
  • 5
  • 15
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."

Rajesh Kaushik
  • 1,471
  • 1
  • 11
  • 16
  • 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.. – austin_ce Jul 20 '15 at 16:14