pythonmongodbtestingmockingmongomock

Insert ObjectId into mongodb


I'm working on a mongo database which, for some reason, has the user id stored as ObjectId.

In order to test some functions, I'd like to be able to populate a test database - for example, as follows:

import mongomock
from bson import ObjectId

client = mongomock.MongoClient("mongodb://localhost:27017/test-database")
database = client.get_default_database()
database.test_collection.insert({'_id': ObjectId('my_user_id'), 'value': 'my_value'})

However, running this returns

InvalidId: 'my_user_id' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string

How can I correctly insert an ObjectId object into my test database, so I can test querying it using

database.test_collection.find_one({'user': ObjectId('my_user_id')})

(which works fine when I query the real database)?


Solution

  • You need to use, as the InvalidId message states, a 12-byte 'binary' input or a 24-character string of hexadecimal characters.

    So, if you wan to use something like 'my_user_id' you'll need to use the binary or hex representation, also, is missing two characters to by 12-byte or 24-hex.

    For example, if your user id is 'my_user_id00', then you can use any of these:

    database.test_collection.find_one({'user': ObjectId(b'my_user_id00')})
    
    database.test_collection.find_one({'user': ObjectId('6d795f757365725f69643030')})
    

    You can find more info on the mongoDB API docs.