MongoEngine / MongoEngine/mongoengine

`save` after `switch_collection` save only the document's id

Open
#2,190 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
4.3k
Forks
1.2k
Avg merge
4h 41m
Merged PRs (30d)
11

Description

I have a very strange behaviour when saving documents after using the switch_collection method. It saves the document on a new collection, but without the value of its fields, only with the _id field.

Can be reproduced using the following code:

import mongoengine as me


class ObjectA(me.Document):
    name = me.StringField()

def test_strange_behaviour():
    a_0 = ObjectA(name="a_0")
    a_0.save()

    a_1 = ObjectA(name="a_1")
    a_1.save()
    
    a_1.switch_collection("new_collection", keep_created=False)
    a_1.id = a_0.id
    a_1.save()

    print(a_1._collection)
    print(a_1._collection.find_one(a_1.id))

When calling the test_strange_behaviour function, the code prints something like that:

Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary(), connecttimeoutms=30000, heartbeatfrequencyms=3000, ssl=False), 'engine'), 'new_collection')
{'_id': ObjectId('5dc57611dba04ca06410e477')}

As you can see, the last print shows that the document created on the new_collection collection contains only the _id field, and not the name field.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the provided test_strange_behaviour reproduction with MongoDB and inspect the switch_collection and save entry points. Confirm that saving after switching to new_collection preserves the document's name field, not only its _id.

Written by the indexing model from the issue text.

Assessment

Tech stack
mongodb, python
Domain
databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.