MongoEngine / MongoEngine/mongoengine

fileField saved in default db even after switch_db()

Open
#1,301 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

files are getting stored in default db even with using switch_db()

Please refer the below code that demostrates the case.
Mongo engine VERSION = 0.10.6

#models.py
from mongoengine import FileField, Document, StringField 
from mongoengine import connect, register_connection

connect('ets', alias='default')
register_connection('ets_archive','ets_archive')

class Mediafile(Document):
    content_type = StringField(max_length=255, required=True)
    file_name = StringField(max_length=1024, required=True)
    file_member = FileField( default=None)
from models import Mediafile
from mongoengine.context_managers import switch_db

def save_db():
    with switch_db(Mediafile, 'ets_archive') as Mediafile_export_db:
        mediafile = Mediafile_export_db()
        mediafile.content_type = 'text/plain'
        mediafile.file_name = 'new_db.txt'
        mediafile.file_member.new_file()
        mediafile.file_member.write('new db'.encode("UTF-8"))
        mediafile.file_member.close()
        mediafile.save()

if __name__ == '__main__':
    save_db()

When I run test.py the file is stored to the default database.
Note there Mediafile Document is still stored in the new archive database. Its only the (gridfs)file thats stored in the default database instead of database named 'ets_archive'

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 with the models.py and test.py reproduction, then inspect FileField/GridFS handling and the switch_db context manager. Verify how the database alias is selected for the document and its file. Done means both the Mediafile document and its GridFS file are stored in ets_archive rather than the default database.

Written by the indexing model from the issue text.

Assessment

Tech stack
mongodb, python
Domain
databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.